using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// AI Agent 对话框
    /// </summary>
    public partial class AgentChatDialog : Window
    {
        private readonly ILogger<AgentChatDialog> _logger;
        private readonly AgentToolService _agentToolService;
        private readonly IAIService _aiService;
        private readonly IProjectService _projectService;
        private readonly IAIToolsService _aiToolsService;
        private readonly ToolCallExampleLibrary _exampleLibrary;
        private readonly ToolCallPerformanceMonitor _performanceMonitor;
        private readonly ProjectScanService _projectScanService;
        private readonly ToolCallCompatibilityService _toolCompatibilityService;
        private CancellationTokenSource? _cancellationTokenSource;

        // 当前项目信息
        public Project? CurrentProject { get; set; }

        // 选中的项目信息
        private ProjectInfo? _selectedProjectInfo;

        // 扫描到的项目列表
        private List<ProjectInfo> _availableProjects = new();

        // 对话历史
        private readonly List<ChatMessage> _chatHistory = new();

        public AgentChatDialog(
            ILogger<AgentChatDialog> logger,
            AgentToolService agentToolService,
            IAIService aiService,
            IProjectService projectService,
            IAIToolsService aiToolsService)
        {
            InitializeComponent();
            _logger = logger;
            _agentToolService = agentToolService;
            _aiService = aiService;
            _projectService = projectService;
            _aiToolsService = aiToolsService;
            _exampleLibrary = new ToolCallExampleLibrary();
            _performanceMonitor = new ToolCallPerformanceMonitor(_logger);
            _projectScanService = new ProjectScanService(_logger as ILogger<ProjectScanService> ??
                Microsoft.Extensions.Logging.Abstractions.NullLogger<ProjectScanService>.Instance);
            _toolCompatibilityService = new ToolCallCompatibilityService(
                _logger as ILogger<ToolCallCompatibilityService> ??
                Microsoft.Extensions.Logging.Abstractions.NullLogger<ToolCallCompatibilityService>.Instance,
                _agentToolService,
                _projectService as ProjectService);

            InitializeUI();
        }

        public AgentChatDialog(IServiceProvider serviceProvider)
        {
            InitializeComponent();
            _logger = serviceProvider.GetRequiredService<ILogger<AgentChatDialog>>();
            _agentToolService = serviceProvider.GetRequiredService<AgentToolService>();
            _aiService = serviceProvider.GetRequiredService<IAIService>();
            _projectService = serviceProvider.GetRequiredService<IProjectService>();
            _aiToolsService = serviceProvider.GetRequiredService<IAIToolsService>();
            _exampleLibrary = new ToolCallExampleLibrary();
            _performanceMonitor = new ToolCallPerformanceMonitor(_logger);
            _projectScanService = new ProjectScanService(_logger as ILogger<ProjectScanService> ??
                Microsoft.Extensions.Logging.Abstractions.NullLogger<ProjectScanService>.Instance);
            _toolCompatibilityService = new ToolCallCompatibilityService(
                _logger as ILogger<ToolCallCompatibilityService> ??
                Microsoft.Extensions.Logging.Abstractions.NullLogger<ToolCallCompatibilityService>.Instance,
                _agentToolService,
                _projectService as ProjectService);

            InitializeUI();
        }

        private async void InitializeUI()
        {
            try
            {
                // 设置基本UI状态
                UpdateStatus("就绪", Brushes.Green);
                UpdateToolStatus("初始化中...", Brushes.Orange);

                // 添加键盘事件处理
                this.KeyDown += OnKeyDown;
                this.Focusable = true;

                // 设置项目信息（如果已有当前项目）
                if (CurrentProject != null)
                {
                    UpdateProjectInfo();
                }
                else
                {
                    ProjectInfoText.Text = "当前项目: 未选择";
                    UpdateProjectSyncStatus("hidden");
                }

                // 延迟加载项目列表，避免初始化时的服务依赖问题
                _ = DelayedInitializeProjectsAsync();

                // 添加工具调用兼容性欢迎信息
                AddWelcomeMessage();

                _logger.LogInformation("AI Agent对话框基本初始化完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "AI Agent对话框初始化失败");
                UpdateToolStatus("初始化失败", Brushes.Red);
            }
        }

        /// <summary>
        /// 延迟初始化项目列表
        /// </summary>
        private async Task DelayedInitializeProjectsAsync()
        {
            try
            {
                // 等待一小段时间，确保主窗口的服务已经准备好
                await Task.Delay(500);

                UpdateToolStatus("加载项目列表...", Brushes.Orange);

                // 尝试扫描并加载项目列表
                await ScanAndLoadProjectsAsync();

                UpdateToolStatus("工具就绪", Brushes.Green);
                _logger.LogInformation("AI Agent对话框项目列表初始化完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "延迟初始化项目列表失败");
                UpdateToolStatus("基本模式", Brushes.Orange);

                // 提供基本功能
                try
                {
                    await InitializeBasicModeAsync();
                }
                catch (Exception basicEx)
                {
                    _logger.LogError(basicEx, "初始化基本模式失败");
                    UpdateToolStatus("功能受限", Brushes.Red);
                }
            }
        }

        /// <summary>
        /// 初始化基本模式（当完整初始化失败时，线程安全版本）
        /// </summary>
        private async Task InitializeBasicModeAsync()
        {
            try
            {
                await Dispatcher.InvokeAsync(() =>
                {
                    // 清空项目选择列表
                    _availableProjects.Clear();

                    // 添加"无项目"选项
                    _availableProjects.Add(new ProjectInfo
                    {
                        Name = "无项目",
                        Path = "",
                        Type = ProjectType.Unknown,
                        Description = "基本模式 - 未选择项目",
                        IsActive = false,
                        FileCount = 0,
                        MarkdownFileCount = 0,
                        Size = 0,
                        CreatedTime = DateTime.Now,
                        LastModifiedTime = DateTime.Now,
                        MainFiles = new List<string>(),
                        Tags = new List<string> { "基本模式" }
                    });

                    // 如果有当前项目，添加到列表
                    if (CurrentProject != null)
                    {
                        var currentProjectInfo = ConvertToProjectInfo(CurrentProject);
                        currentProjectInfo.Tags.Add("基本模式");
                        _availableProjects.Add(currentProjectInfo);

                        // 设置ItemsSource并选择当前项目
                        ProjectSelectionComboBox.ItemsSource = _availableProjects;
                        ProjectSelectionComboBox.SelectedIndex = 1; // 选择当前项目

                        AddSystemMessage($"🔧 基本模式已启用，当前项目: {CurrentProject.Name}");
                        _logger.LogInformation($"基本模式已启用，当前项目: {CurrentProject.Name}");
                    }
                    else
                    {
                        // 设置ItemsSource并选择"无项目"
                        ProjectSelectionComboBox.ItemsSource = _availableProjects;
                        ProjectSelectionComboBox.SelectedIndex = 0;

                        AddSystemMessage("🔧 基本模式已启用，功能可能受限");
                        _logger.LogInformation("基本模式已启用，无当前项目");
                    }

                    UpdateToolStatus("基本模式就绪", Brushes.Green);
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化基本模式失败");

                // 最后的备用方案
                try
                {
                    await Dispatcher.InvokeAsync(() =>
                    {
                        UpdateToolStatus("功能受限", Brushes.Red);
                        AddSystemMessage("⚠️ 基本模式初始化失败，功能可能受限");
                    });
                }
                catch (Exception finalEx)
                {
                    _logger.LogError(finalEx, "最终错误处理也失败");
                }

                throw;
            }
        }

        /// <summary>
        /// 更新项目信息显示
        /// </summary>
        public void UpdateProjectInfo()
        {
            try
            {
                // 显示同步进行中状态
                UpdateProjectSyncStatus("syncing");

                // 优先显示选中的项目信息
                if (_selectedProjectInfo != null)
                {
                    ProjectInfoText.Text = $"当前项目: {_selectedProjectInfo.Name} ({_selectedProjectInfo.TypeDisplayName})";

                    // 创建临时项目对象来设置访问范围
                    var tempProject = new Project
                    {
                        Name = _selectedProjectInfo.Name,
                        RootPath = _selectedProjectInfo.Path
                    };

                    // 先设置项目（这会设置允许的访问范围）
                    _agentToolService.SetCurrentProject(tempProject);
                    // 然后设置工作目录（这会验证路径是否在允许范围内）
                    _agentToolService.SetWorkingDirectory(_selectedProjectInfo.Path);
                    _logger.LogInformation($"Agent助手已切换到项目: {_selectedProjectInfo.Name} at {_selectedProjectInfo.Path}");
                }
                else if (CurrentProject != null)
                {
                    ProjectInfoText.Text = $"当前项目: {CurrentProject.Name}";
                    _agentToolService.SetCurrentProject(CurrentProject);
                    _logger.LogInformation($"Agent助手已同步项目: {CurrentProject.Name}");
                }
                else
                {
                    ProjectInfoText.Text = "当前项目: 未选择";
                    _agentToolService.SetCurrentProject(null);
                    _logger.LogInformation("Agent助手已清除项目信息");
                }

                // 显示同步成功状态
                UpdateProjectSyncStatus("success");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新项目信息显示时发生错误");
                // 显示同步失败状态
                UpdateProjectSyncStatus("error");
                throw; // 重新抛出异常以便上层处理
            }
        }

        /// <summary>
        /// 更新项目同步状态指示器
        /// </summary>
        /// <param name="status">状态：syncing, success, error, hidden</param>
        private void UpdateProjectSyncStatus(string status)
        {
            try
            {
                Dispatcher.Invoke(() =>
                {
                    switch (status.ToLower())
                    {
                        case "syncing":
                            ProjectSyncStatusIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.Sync;
                            ProjectSyncStatusIcon.Foreground = Brushes.Orange;
                            ProjectSyncStatusIcon.ToolTip = "正在同步项目信息...";
                            ProjectSyncStatusIcon.Visibility = Visibility.Visible;
                            break;
                        case "success":
                            ProjectSyncStatusIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle;
                            ProjectSyncStatusIcon.Foreground = Brushes.Green;
                            ProjectSyncStatusIcon.ToolTip = "项目信息同步成功";
                            ProjectSyncStatusIcon.Visibility = Visibility.Visible;
                            // 3秒后自动隐藏成功状态
                            _ = Task.Delay(3000).ContinueWith(_ =>
                            {
                                Dispatcher.Invoke(() => ProjectSyncStatusIcon.Visibility = Visibility.Collapsed);
                            });
                            break;
                        case "error":
                            ProjectSyncStatusIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.AlertCircle;
                            ProjectSyncStatusIcon.Foreground = Brushes.Red;
                            ProjectSyncStatusIcon.ToolTip = "项目信息同步失败";
                            ProjectSyncStatusIcon.Visibility = Visibility.Visible;
                            break;
                        case "hidden":
                        default:
                            ProjectSyncStatusIcon.Visibility = Visibility.Collapsed;
                            break;
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新项目同步状态指示器失败");
            }
        }

        /// <summary>
        /// 同步当前项目（外部调用，线程安全版本）
        /// </summary>
        public void SyncCurrentProject(Models.Project? project)
        {
            try
            {
                // 确保在UI线程中执行UI相关操作
                if (!Dispatcher.CheckAccess())
                {
                    Dispatcher.Invoke(() => SyncCurrentProject(project));
                    return;
                }

                // 显示同步开始状态
                UpdateProjectSyncStatus("syncing");

                SetCurrentProject(project);

                // 添加系统消息通知项目变更
                if (project != null)
                {
                    AddSystemMessage($"✅ 已同步项目: {project.Name}");
                    _logger.LogInformation($"Agent助手项目同步成功: {project.Name} (路径: {project.RootPath})");
                }
                else
                {
                    AddSystemMessage("📂 已退出当前项目");
                    _logger.LogInformation("Agent助手已清除项目信息");
                }

                // 同步成功，状态会在UpdateProjectInfo中设置
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"同步项目信息时发生错误: {project?.Name ?? "null"}");

                try
                {
                    // 显示错误状态
                    UpdateProjectSyncStatus("error");

                    // 提供用户友好的错误信息
                    if (project != null)
                    {
                        AddSystemMessage($"⚠️ 项目同步部分失败: {project.Name}，但基本功能仍可使用");

                        // 确保项目信息至少被设置，即使UI同步失败
                        CurrentProject = project;

                        // 尝试基本的UI更新
                        if (ProjectInfoText != null)
                        {
                            ProjectInfoText.Text = $"当前项目: {project.Name}";
                        }

                        // 设置Agent工具服务
                        if (_agentToolService != null)
                        {
                            _agentToolService.SetCurrentProject(project);
                        }

                        _logger.LogInformation($"Agent助手已设置基本项目信息: {project.Name}");
                    }
                    else
                    {
                        AddSystemMessage("⚠️ 退出项目时发生错误，请手动刷新");
                    }
                }
                catch (Exception recoveryEx)
                {
                    _logger.LogError(recoveryEx, "项目同步错误恢复失败");

                    // 最后的备用方案：至少设置项目引用
                    try
                    {
                        CurrentProject = project;
                        if (project != null)
                        {
                            AddSystemMessage($"⚠️ 项目 {project.Name} 已设置，但可能存在显示问题");
                        }
                    }
                    catch (Exception finalEx)
                    {
                        _logger.LogError(finalEx, "最终备用方案也失败");
                    }
                }
            }
        }

        /// <summary>
        /// 刷新项目列表（外部调用，用于主窗口通知项目服务已准备好）
        /// </summary>
        public async Task RefreshProjectListAsync()
        {
            try
            {
                _logger.LogInformation("收到刷新项目列表请求");

                // 检查是否需要在UI线程中执行
                bool needsReinitialize = false;
                await Dispatcher.InvokeAsync(() =>
                {
                    needsReinitialize = ToolStatusText.Text.Contains("基本模式") || ToolStatusText.Text.Contains("功能受限");
                });

                // 如果当前处于基本模式，尝试重新初始化完整功能
                if (needsReinitialize)
                {
                    UpdateToolStatus("重新初始化...", Brushes.Orange);
                    await DelayedInitializeProjectsAsync();
                }
                else
                {
                    // 正常刷新项目列表
                    await ScanAndLoadProjectsAsync();
                }

                AddSystemMessage("🔄 项目列表已刷新");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "刷新项目列表失败");
                AddSystemMessage("⚠️ 刷新项目列表失败，请稍后重试");
            }
        }

        private void MessageTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (Keyboard.Modifiers == ModifierKeys.Control)
                {
                    // Ctrl+Enter 发送消息
                    Send_Click(sender, e);
                    e.Handled = true;
                }
                else if (Keyboard.Modifiers == ModifierKeys.Shift)
                {
                    // Shift+Enter 换行，不处理
                }
                else
                {
                    // 单独Enter发送消息
                    Send_Click(sender, e);
                    e.Handled = true;
                }
            }
        }

        private async void Send_Click(object sender, RoutedEventArgs e)
        {
            var message = MessageTextBox.Text.Trim();
            if (string.IsNullOrEmpty(message))
                return;

            try
            {
                // 清空输入框
                MessageTextBox.Text = string.Empty;

                // 添加用户消息到界面
                AddUserMessage(message);

                // 更新状态
                UpdateStatus("AI正在思考...", Brushes.Orange);
                SendButton.IsEnabled = false;

                // 取消之前的请求
                _cancellationTokenSource?.Cancel();
                _cancellationTokenSource = new CancellationTokenSource();

                // 发送到AI并获取响应
                await ProcessUserMessageAsync(message, _cancellationTokenSource.Token);
            }
            catch (OperationCanceledException)
            {
                UpdateStatus("已取消", Brushes.Gray);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理用户消息时发生错误");
                AddAIMessage($"抱歉，处理您的消息时发生错误：{ex.Message}");
                UpdateStatus("错误", Brushes.Red);
            }
            finally
            {
                SendButton.IsEnabled = true;
                UpdateStatus("就绪", Brushes.Green);
            }
        }

        private async Task ProcessUserMessageAsync(string message, CancellationToken cancellationToken)
        {
            // 检查特殊命令
            if (await HandleSpecialCommandsAsync(message))
            {
                return;
            }

            // 添加用户消息到历史
            _chatHistory.Add(new ChatMessage { Role = "user", Content = message });

            // 构建系统提示
            var systemPrompt = await BuildSystemPromptAsync();

            // 构建对话上下文
            var conversationContext = BuildConversationContext();

            // 调用AI服务
            var aiResponse = await _aiService.GenerateTextAsync(
                $"{systemPrompt}\n\n{conversationContext}\n\nUser: {message}\n\nAssistant:",
                2000, 0.7f);

            cancellationToken.ThrowIfCancellationRequested();

            // 处理AI响应中的工具调用
            var processedResponse = await ProcessAIResponseAsync(aiResponse, cancellationToken);

            // 添加AI响应到界面和历史
            AddAIMessage(processedResponse);
            _chatHistory.Add(new ChatMessage { Role = "assistant", Content = processedResponse });

            // 限制历史长度
            if (_chatHistory.Count > 20)
            {
                _chatHistory.RemoveRange(0, _chatHistory.Count - 20);
            }
        }
        private string BuildConversationContext()
        {
            try
            {
                // 将最近的聊天记录拼接为简短上下文，限制长度避免超长
                var recent = _chatHistory.Count <= 10 ? _chatHistory : _chatHistory.GetRange(_chatHistory.Count - 10, 10);
                var sb = new System.Text.StringBuilder();
                foreach (var msg in recent)
                {
                    sb.AppendLine($"{msg.Role}: {msg.Content}");
                }
                return sb.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }


        private async Task<string> BuildSystemPromptAsync()
        {
            // 获取所有可用工具
            var availableTools = await _aiToolsService.GetAvailableToolsAsync();
            var toolsByCategory = availableTools.GroupBy(t => t.Category).ToDictionary(g => g.Key, g => g.ToList());

            // 获取当前AI模型信息和能力配置
            var currentModel = _aiService.GetCurrentModel();
            var modelName = currentModel?.Name ?? "unknown";
            var modelCapabilities = EnhancedAIAssistantConfig.GetModelCapabilities(modelName);

            var systemPrompt = BuildEnhancedSystemPrompt(toolsByCategory, modelCapabilities);
            return systemPrompt;
        }

        private string BuildEnhancedSystemPrompt(Dictionary<string, List<AITool>> toolsByCategory, ModelCapabilities modelCapabilities)
        {
            var prompt = BuildBaseSystemPrompt(modelCapabilities);

            // 根据模型能力添加不同的工具调用指导
            prompt += BuildToolCallGuidance(modelCapabilities);

            // 添加工具列表
            prompt += BuildToolsDescription(toolsByCategory);

            // 添加使用示例
            prompt += BuildUsageExamples(modelCapabilities);

            // 添加示例库中的最佳实践
            prompt += BuildExampleLibraryGuidance();

            return prompt;
        }

        private string BuildBaseSystemPrompt(ModelCapabilities capabilities)
        {
            // 获取当前项目信息
            var currentProjectInfo = GetCurrentProjectContext();

            var basePrompt = $@"# AI助手系统指令

你是一个专业的AI助手，具备强大的工具调用能力。你可以帮助用户完成各种文件操作、代码分析、内容创作等任务。

## 核心能力
- 📁 文件和目录管理
- 🔍 智能搜索和分析
- ✍️ 内容创作和编辑
- 🌐 网络搜索和信息获取
- 🛠️ 代码分析和项目管理
- 📋 MD项目识别和操作

## 当前工作环境
{currentProjectInfo}

## 项目操作能力
你可以识别和操作以下类型的项目：
- **Markdown项目**: 包含大量.md文件的项目，适合文档编写和知识管理
- **小说项目**: 包含章节文件的创作项目，支持故事情节分析和续写
- **文档项目**: 包含各种文档文件的项目，适合技术文档和报告
- **代码项目**: 包含源代码的开发项目，支持代码分析和重构
- **混合项目**: 包含多种类型文件的综合项目

## 工作原则
1. **主动思考**: 分析用户需求，确定最佳的工具组合
2. **精确执行**: 使用正确的工具调用格式，确保参数准确
3. **结果验证**: 检查工具执行结果，必要时进行调整
4. **用户友好**: 提供清晰的执行过程说明和结果总结
5. **项目感知**: 根据当前项目类型调整工作方式和建议

";

            // 根据模型特性添加特殊指导
            if (capabilities.SupportsThinkingChains)
            {
                basePrompt += @"
## 思维链处理
你支持思维链推理。在复杂任务中，可以使用 <think>...</think> 标签进行思考，最终结果用 <output>...</output> 标签包装。

";
            }

            // 追加“自主规划”资料摘要，帮助Agent自动参考
            var planningContext = TryLoadPlanningContextSummary();
            if (!string.IsNullOrWhiteSpace(planningContext))
            {
                basePrompt += "\n## 项目资料（来自自主规划文件）\n" + planningContext + "\n";
            }

            return basePrompt;
        }

        private string BuildToolCallGuidance(ModelCapabilities capabilities)
        {
            if (capabilities.SupportsFunctionCalling)
            {
                return BuildNativeFunctionCallGuidance();
            }
            else
            {
                return BuildTextBasedToolCallGuidance(capabilities);
            }
        }

        private string BuildNativeFunctionCallGuidance()
        {
            return @"
## 工具调用方式（原生函数调用）
你的模型支持原生函数调用，请使用标准的函数调用格式。

";
        }

        private string BuildTextBasedToolCallGuidance(ModelCapabilities capabilities)
        {
            var guidance = @"
## 工具调用方式（文本格式）

### 基础工具调用格式
```
[TOOL:工具名]参数[/TOOL]
```

### 高级工具调用格式
```
[AITOOL:工具ID]{""参数名"":""参数值""}[/AITOOL]
```

### 智能工具调用（推荐）
当你需要执行某个操作时，可以用自然语言描述你的意图，系统会自动识别并执行相应的工具：

```
[ACTION:操作描述]
```

例如：
- [ACTION:读取config.json文件的内容]
- [ACTION:在项目目录下创建一个名为test.txt的文件，内容是Hello World]
- [ACTION:搜索项目中包含""AI服务""的所有文件]

### 工具调用规则
1. **精确性**: 参数必须准确，路径使用正斜杠或反斜杠
2. **完整性**: 提供所有必需的参数
3. **顺序性**: 按逻辑顺序执行多个工具
4. **验证性**: 检查工具执行结果，必要时重试

";

            // 根据模型特性添加额外指导
            if (capabilities.RecommendedPromptStyle == PromptStyle.Detailed)
            {
                guidance += @"
### 详细模式建议
由于你的模型适合详细说明，建议在工具调用前后提供详细的说明：
- 说明为什么选择这个工具
- 解释参数的含义
- 预期的执行结果

";
            }

            return guidance;
        }

        private string BuildToolsDescription(Dictionary<string, List<AITool>> toolsByCategory)
        {
            var toolsDescription = @"
## 可用工具列表

### 📁 基础文件操作工具
• **read_file** - 读取文件完整内容
  格式: [TOOL:read_file]文件路径[/TOOL]
  示例: [TOOL:read_file]config.json[/TOOL]

• **write_file** - 创建新文件
  格式: [TOOL:write_file]文件路径|文件内容[/TOOL]
  示例: [TOOL:write_file]test.txt|Hello World[/TOOL]

• **list_files** - 列出目录文件
  格式: [TOOL:list_files]目录路径[/TOOL]
  示例: [TOOL:list_files].[/TOOL]

• **update_file_content** - 智能更新文件内容
  格式: [TOOL:update_file_content]文件路径|操作类型|内容[/TOOL]
  示例: [TOOL:update_file_content]readme.md|append|新增内容[/TOOL]

• **smart_search** - 智能搜索文件内容
  格式: [TOOL:smart_search]搜索关键词[/TOOL]
  示例: [TOOL:smart_search]AI服务[/TOOL]

";

            // 添加高级工具描述
            foreach (var category in toolsByCategory)
            {
                toolsDescription += $"\n### 🔧 {category.Key}\n";
                foreach (var tool in category.Value)
                {
                    toolsDescription += $"• **{tool.Id}** - {tool.Description}\n";
                    if (!string.IsNullOrEmpty(tool.Usage))
                    {
                        toolsDescription += $"  用法: {tool.Usage}\n";
                    }
                    toolsDescription += $"  格式: [AITOOL:{tool.Id}]{{\"参数\":\"值\"}}[/AITOOL]\n\n";
                }
            }

            return toolsDescription;
        }

        private string GetToolParametersDescription(string toolId)
        {
            // 返回工具参数的简单描述
            return toolId switch
            {
                "search-codebase" => "query, fileTypes?",
                "web-search" => "query, language?",
                "view-files" => "paths, maxFiles?",
                "list-dir" => "path?",
                "write-to-file" => "path, content",
                "update-file" => "path, operation, content",
                "run-command" => "command, workingDir?",
                "content-analyzer" => "content, type?",
                _ => "参数"
            };
        }

        private string GetCategoryIcon(string category)
        {
            return category switch
            {
                "代码搜索" => "🔍",
                "文件操作" => "📁",
                "开发辅助" => "🛠️",
                "网络工具" => "🌐",
                "MCP集成" => "🔧",
                "AI辅助" => "🤖",
                "内容分析" => "📊",
                _ => "🔧"
            };
        }

        private string BuildUsageExamples(ModelCapabilities capabilities)
        {
            if (capabilities.SupportsFunctionCalling)
            {
                return @"
## 使用示例（原生函数调用）
请使用标准的函数调用格式来调用工具。

";
            }

            var examples = @"
## 使用示例

### 文件操作示例
**用户**: 请帮我创建一个配置文件
**助手**: 我来帮您创建配置文件。
[TOOL:write_file]config.json|{""version"":""1.0"",""settings"":{}}[/TOOL]
配置文件已创建完成。

**用户**: 读取刚才创建的配置文件
**助手**: 我来读取配置文件内容。
[TOOL:read_file]config.json[/TOOL]

### 智能搜索示例
**用户**: 查找项目中所有的服务类
**助手**: 我来搜索项目中的服务类。
[AITOOL:search-codebase]{""query"":""service class"",""fileTypes"":""cs""}[/AITOOL]

### 自然语言工具调用示例
**用户**: 帮我分析一下项目结构
**助手**: 我来分析项目结构。
[ACTION:列出当前目录的所有文件和子目录]
[ACTION:搜索项目中的主要代码文件]

### 复合操作示例
**用户**: 搜索网络上的C#教程并保存到文件
**助手**: 我来为您搜索C#教程并保存。
[AITOOL:web-search]{""query"":""C# 教程 2024"",""language"":""zh-CN""}[/AITOOL]
[TOOL:write_file]csharp_tutorials.txt|搜索到的教程内容[/TOOL]

## 重要提醒
1. **工具调用必须准确**: 确保工具名称、参数格式正确
2. **路径使用规范**: 文件路径使用正确的分隔符
3. **参数完整性**: 提供所有必需的参数
4. **结果验证**: 检查工具执行结果，必要时进行调整
5. **用户体验**: 在执行工具前后提供清晰的说明

现在，请根据用户的需求，选择合适的工具来完成任务。记住要主动思考、精确执行、验证结果。

";

            // 根据模型风格调整示例
            if (capabilities.RecommendedPromptStyle == PromptStyle.ThinkingChain)
            {
                examples += @"
### 思维链示例
**用户**: 帮我分析项目结构并创建文档
**助手**: <think>
用户想要分析项目结构并创建文档，我需要：
1. 先列出项目文件
2. 分析项目结构
3. 创建相应的文档
</think>

<output>
我来帮您分析项目结构并创建文档。
[TOOL:list_files].[/TOOL]
[ACTION:分析项目结构并生成文档]
</output>

";
            }

            return examples;
        }

        private string BuildExampleLibraryGuidance()
        {
            return @"
## 工具使用最佳实践

### 常用工具调用模式

**文件操作模式**:
- 读取文件: [TOOL:read_file]文件路径[/TOOL]
- 创建文件: [TOOL:write_file]文件路径|文件内容[/TOOL]
- 列出目录: [TOOL:list_files]目录路径[/TOOL]

**搜索模式**:
- 内容搜索: [TOOL:smart_search]关键词[/TOOL]
- 代码搜索: [AITOOL:search-codebase]{""query"":""搜索内容""}[/AITOOL]
- 网络搜索: [AITOOL:web-search]{""query"":""搜索内容"",""language"":""zh-CN""}[/AITOOL]

**智能推荐模式**:
当你不确定使用哪个工具时，可以描述你的意图，系统会自动推荐合适的工具：
- [ACTION:读取项目配置文件]
- [ACTION:搜索代码中的服务类]
- [ACTION:创建一个测试文件]

### 参数格式要求
1. **基础工具**: 使用简单的字符串参数，多个参数用|分隔
2. **高级工具**: 使用JSON格式参数，确保语法正确
3. **路径参数**: 使用相对路径，注意路径分隔符
4. **内容参数**: 较长内容建议使用简洁描述

### 错误处理
- 工具名称错误时，系统会自动纠正
- 参数格式错误时，系统会提供默认值
- 执行失败时，系统会提供错误信息和建议

🔍 **高级检索分析工具**：
• scan_project_structure([path]) - 递归扫描项目结构，获取完整目录树
• get_file_summary(filePath) - 生成文件内容摘要和统计信息
• analyze_file_relationships([path]) - 分析文件间的关联关系
• deep_content_search(keyword|[path]) - 深度搜索内容并提供上下文
• get_project_overview([path]) - 生成项目整体概览和分析
• extract_key_information(filePath|[type]) - 提取关键信息（角色/地点/事件）
• compare_files(file1|file2) - 比较两个文件的差异
• get_content_statistics([path]) - 获取详细的内容统计信息

🎨 **内容创作工具**：
• analyze_story(content) - 深度分析故事内容，提供专业建议
• generate_content(prompt|type) - 生成新内容（章节、角色、情节等）
";
        }

        /// <summary>
        /// 从当前项目的“自主规划”文件夹加载若干最新文件的摘要
        /// </summary>
        private string TryLoadPlanningContextSummary()
        {
            try
            {
                var root = GetCurrentProjectRootPath();
                if (string.IsNullOrWhiteSpace(root)) return string.Empty;

                var planningDir = System.IO.Path.Combine(root, "自主规划");
                if (!Directory.Exists(planningDir)) return string.Empty;

                // 取最近的若干文本文件
                var files = Directory.GetFiles(planningDir, "*.txt", SearchOption.TopDirectoryOnly)
                    .Select(p => new System.IO.FileInfo(p))
                    .OrderByDescending(f => f.CreationTime)
                    .Take(5)
                    .ToList();
                if (files.Count == 0) return string.Empty;

                var sb = new System.Text.StringBuilder();
                foreach (var f in files)
                {
                    string text = string.Empty;
                    try { text = File.ReadAllText(f.FullName); } catch { }
                    if (string.IsNullOrWhiteSpace(text)) continue;

                    // 简要摘要（前500字）
                    var snippet = text.Length > 500 ? text.Substring(0, 500) + "..." : text;
                    sb.AppendLine($"- {f.Name} ({f.Length / 1024} KB)");
                    sb.AppendLine(snippet.Replace("\r\n", " ").Replace("\n", " "));
                    sb.AppendLine();
                }

                return sb.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "加载自主规划上下文摘要失败");
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取当前项目根路径
        /// </summary>
        private string? GetCurrentProjectRootPath()
        {
            try
            {
                if (_selectedProjectInfo != null && !string.IsNullOrWhiteSpace(_selectedProjectInfo.Path))
                {
                    return _selectedProjectInfo.Path;
                }
                if (CurrentProject != null && !string.IsNullOrWhiteSpace(CurrentProject.RootPath))
                {
                    return CurrentProject.RootPath;
                }
                if (Application.Current?.MainWindow is MainWindow main &&
                    !string.IsNullOrWhiteSpace(main?.DocumentEditorControl?.CurrentProjectPath))
                {
                    return main.DocumentEditorControl.CurrentProjectPath;
                }
            }
            catch { }
            return null;
        }



        private async void RunDiagnostics_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 优先使用独立的诊断窗口
                var diag = new DiagnosticsWindow(DocumentCreationSystem.App.ServiceProvider);
                diag.Owner = this;
                diag.Show();
            }
            catch (Exception ex)
            {
                AddToolMessage($"❌ 打开诊断面板失败: {ex.Message}");
            }
        }

        private string? _lastPreviewDiffBase64;

        private async void ApplyPatchBase64_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var ofd = new OpenFileDialog
                {
                    Title = "选择包含统一diff文本的文件",
                    Filter = "Text Files (*.txt;*.patch)|*.txt;*.patch|All Files (*.*)|*.*"
                };
                if (ofd.ShowDialog() == true)
                {
                    var text = await File.ReadAllTextAsync(ofd.FileName);
                    var base64 = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
                    var result = await _agentToolService.ExecuteToolAsync("apply_patch_base64", base64);
                    AddToolMessage(result);
                }
            }
            catch (Exception ex)
            {
                AddToolMessage($"❌ 应用补丁失败: {ex.Message}");
            }
        }

        private void PreviewPatch_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var w = new PatchPreviewWindow(DocumentCreationSystem.App.ServiceProvider);
                w.Owner = this;
                w.Show();
            }
            catch (Exception ex)
            {
                AddToolMessage($"❌ 打开补丁预览失败: {ex.Message}");
            }
        }

        private async void ApplyLastPreview_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(_lastPreviewDiffBase64))
                {
                    AddToolMessage("⚠️ 没有可应用的预览补丁，请先执行‘预览补丁’。");
                    return;
                }
                var result = await _agentToolService.ExecuteToolAsync("apply_patch_base64", _lastPreviewDiffBase64);
                AddToolMessage(result);
            }
            catch (Exception ex)
            {
                AddToolMessage($"❌ 应用上次预览失败: {ex.Message}");
            }
        }

        private async Task<string> ProcessAIResponseAsync(string aiResponse, CancellationToken cancellationToken)
        {
            var processedResponse = aiResponse;

            // 处理思维链（如果存在）
            processedResponse = ProcessThinkingChains(processedResponse);

            // 首先尝试使用兼容性服务处理工具调用
            if (_toolCompatibilityService.ContainsToolCalls(processedResponse))
            {
                try
                {
                    var currentProjectPath = CurrentProject?.RootPath ?? _selectedProjectInfo?.Path;
                    var compatibilityResult = await _toolCompatibilityService.ProcessToolCallsAsync(processedResponse, currentProjectPath);

                    // 如果兼容性服务成功处理了工具调用，直接返回结果
                    if (compatibilityResult != processedResponse)
                    {
                        UpdateToolStatus("✅ 工具调用兼容性处理完成", Brushes.Green);
                        return compatibilityResult;
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, "工具调用兼容性处理失败，回退到原始处理方式");
                    AddToolMessage($"⚠️ 兼容性处理失败，使用原始方式: {ex.Message}");
                }
            }

            // 查找工具调用（原始方式）
            var toolCalls = ExtractToolCalls(processedResponse);

            // 如果没有找到明确的工具调用，尝试智能推荐
            if (toolCalls.Count == 0)
            {
                var recommendedTools = await RecommendToolsForResponse(processedResponse);
                if (recommendedTools.Count > 0)
                {
                    // 询问用户是否执行推荐的工具
                    var recommendation = BuildToolRecommendationMessage(recommendedTools);
                    AddToolMessage($"💡 智能推荐: {recommendation}");

                    // 自动执行高置信度的推荐
                    var highConfidenceTools = recommendedTools.Where(r => r.Confidence > 0.8).ToList();
                    if (highConfidenceTools.Count > 0)
                    {
                        toolCalls.AddRange(highConfidenceTools.Select(r => r.ToolCall));
                        AddToolMessage($"🚀 自动执行 {highConfidenceTools.Count} 个高置信度工具");
                    }
                }
            }

            if (toolCalls.Count == 0)
            {
                return processedResponse;
            }

            UpdateToolStatus($"发现 {toolCalls.Count} 个工具调用", Brushes.Orange);

            for (int i = 0; i < toolCalls.Count; i++)
            {
                var toolCall = toolCalls[i];

                try
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    // 验证和纠错工具调用
                    var validatedToolCall = await ValidateAndCorrectToolCall(toolCall);
                    if (validatedToolCall == null)
                    {
                        AddToolMessage($"❌ 工具调用验证失败: {toolCall.ToolName}");
                        processedResponse = processedResponse.Replace(toolCall.OriginalText, "[工具调用无效]");
                        continue;
                    }

                    UpdateToolStatus($"执行工具 {i + 1}/{toolCalls.Count}: {validatedToolCall.ToolName}", Brushes.Orange);

                    // 显示工具调用信息
                    var toolTypeIcon = validatedToolCall.ToolType == ToolType.Basic ? "🔧" : "⚡";
                    AddToolMessage($"{toolTypeIcon} 执行工具: {validatedToolCall.ToolName}");

                    // 显示参数信息（如果不为空）
                    if (!string.IsNullOrWhiteSpace(validatedToolCall.Parameters))
                    {
                        var paramPreview = validatedToolCall.Parameters.Length > 100 ?
                            validatedToolCall.Parameters.Substring(0, 100) + "..." :
                            validatedToolCall.Parameters;
                        AddToolMessage($"📋 参数: {paramPreview}");
                    }

                    string toolResult;

                    // 开始性能监控
                    using var performanceSession = _performanceMonitor.StartToolCall(
                        validatedToolCall.ToolName, validatedToolCall.Parameters);

                    try
                    {
                        if (validatedToolCall.ToolType == ToolType.Basic)
                        {
                            // 执行基础工具
                            toolResult = await _agentToolService.ExecuteToolAsync(
                                validatedToolCall.ToolName, validatedToolCall.Parameters, cancellationToken);
                        }
                        else
                        {
                            // 执行高级AI工具
                            toolResult = await ExecuteAdvancedToolAsync(validatedToolCall, cancellationToken);
                        }

                        // 标记执行成功
                        performanceSession.MarkSuccess();
                    }
                    catch (Exception toolEx)
                    {
                        // 标记执行失败
                        performanceSession.MarkFailure(toolEx.Message);
                        throw;
                    }

                    // 显示工具结果
                    var resultPreview = toolResult.Length > 200 ?
                        toolResult.Substring(0, 200) + "..." :
                        toolResult;
                    AddToolMessage($"✅ 执行完成: {resultPreview}");

                    // 替换响应中的工具调用为结果
                    processedResponse = processedResponse.Replace(toolCall.OriginalText, toolResult);
                }
                catch (OperationCanceledException)
                {
                    AddToolMessage($"⏹️ 工具执行已取消: {toolCall.ToolName}");
                    processedResponse = processedResponse.Replace(toolCall.OriginalText, "[工具执行已取消]");
                    throw;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"执行工具 {toolCall.ToolName} 失败");
                    AddToolMessage($"❌ 工具执行失败: {toolCall.ToolName} - {ex.Message}");
                    processedResponse = processedResponse.Replace(toolCall.OriginalText, $"[工具执行失败: {ex.Message}]");
                }
            }

            UpdateToolStatus("所有工具执行完成", Brushes.Green);
            return processedResponse;
        }

        private List<ToolCall> ExtractToolCalls(string text)
        {
            var toolCalls = new List<ToolCall>();

            // 提取基础工具调用 [TOOL:工具名]参数[/TOOL]
            ExtractBasicToolCalls(text, toolCalls);

            // 提取高级工具调用 [AITOOL:工具ID]{"参数名":"参数值"}[/AITOOL]
            ExtractAdvancedToolCalls(text, toolCalls);

            // 提取自然语言工具调用 [ACTION:操作描述]
            ExtractActionCalls(text, toolCalls);

            // 智能推断工具调用（基于用户意图）
            ExtractInferredToolCalls(text, toolCalls);

            return toolCalls;
        }

        private void ExtractBasicToolCalls(string text, List<ToolCall> toolCalls)
        {
            var startIndex = 0;

            while (true)
            {
                var toolStart = text.IndexOf("[TOOL:", startIndex);
                if (toolStart == -1) break;

                var toolEnd = text.IndexOf("[/TOOL]", toolStart);
                if (toolEnd == -1) break;

                var toolText = text.Substring(toolStart, toolEnd - toolStart + 7);
                var toolContent = text.Substring(toolStart + 6, toolEnd - toolStart - 6);

                var colonIndex = toolContent.IndexOf(']');
                if (colonIndex > 0)
                {
                    var toolName = toolContent.Substring(0, colonIndex);
                    var parameters = toolContent.Substring(colonIndex + 1);

                    toolCalls.Add(new ToolCall
                    {
                        ToolName = toolName,
                        Parameters = parameters,
                        OriginalText = toolText,
                        ToolType = ToolType.Basic
                    });
                }

                startIndex = toolEnd + 7;
            }
        }

        private void ExtractAdvancedToolCalls(string text, List<ToolCall> toolCalls)
        {
            var startIndex = 0;

            while (true)
            {
                var toolStart = text.IndexOf("[AITOOL:", startIndex);
                if (toolStart == -1) break;

                var toolEnd = text.IndexOf("[/AITOOL]", toolStart);
                if (toolEnd == -1) break;

                var toolText = text.Substring(toolStart, toolEnd - toolStart + 9);
                var toolContent = text.Substring(toolStart + 8, toolEnd - toolStart - 8);

                var colonIndex = toolContent.IndexOf(']');
                if (colonIndex > 0)
                {
                    var toolName = toolContent.Substring(0, colonIndex);
                    var parameters = toolContent.Substring(colonIndex + 1);

                    toolCalls.Add(new ToolCall
                    {
                        ToolName = toolName,
                        Parameters = parameters,
                        OriginalText = toolText,
                        ToolType = ToolType.Advanced
                    });
                }

                startIndex = toolEnd + 9;
            }
        }

        private void ExtractActionCalls(string text, List<ToolCall> toolCalls)
        {
            var startIndex = 0;

            while (true)
            {
                var actionStart = text.IndexOf("[ACTION:", startIndex);
                if (actionStart == -1) break;

                var actionEnd = text.IndexOf("]", actionStart);
                if (actionEnd == -1) break;

                var actionText = text.Substring(actionStart, actionEnd - actionStart + 1);
                var actionDescription = text.Substring(actionStart + 8, actionEnd - actionStart - 8);

                // 将自然语言描述转换为具体的工具调用
                var inferredToolCall = InferToolFromDescription(actionDescription, actionText);
                if (inferredToolCall != null)
                {
                    toolCalls.Add(inferredToolCall);
                }

                startIndex = actionEnd + 1;
            }
        }

        private void ExtractInferredToolCalls(string text, List<ToolCall> toolCalls)
        {
            // 如果没有找到明确的工具调用，尝试从文本中推断用户意图
            if (toolCalls.Count > 0) return;

            var inferredCalls = InferToolCallsFromText(text);
            toolCalls.AddRange(inferredCalls);
        }

        private ToolCall? InferToolFromDescription(string description, string originalText)
        {
            description = description.ToLower().Trim();

            // 文件读取操作
            if (description.Contains("读取") || description.Contains("查看") || description.Contains("打开"))
            {
                var filePath = ExtractFilePathFromDescription(description);
                if (!string.IsNullOrEmpty(filePath))
                {
                    return new ToolCall
                    {
                        ToolName = "read_file",
                        Parameters = filePath,
                        OriginalText = originalText,
                        ToolType = ToolType.Basic
                    };
                }
            }

            // 文件创建操作
            if (description.Contains("创建") || description.Contains("新建") || description.Contains("写入"))
            {
                var fileInfo = ExtractFileCreationInfo(description);
                if (fileInfo.HasValue)
                {
                    return new ToolCall
                    {
                        ToolName = "write_file",
                        Parameters = $"{fileInfo.Value.Path}|{fileInfo.Value.Content}",
                        OriginalText = originalText,
                        ToolType = ToolType.Basic
                    };
                }
            }

            // 目录列表操作
            if (description.Contains("列出") || description.Contains("查看目录") || description.Contains("文件列表"))
            {
                var dirPath = ExtractDirectoryPathFromDescription(description);
                return new ToolCall
                {
                    ToolName = "list_files",
                    Parameters = dirPath ?? ".",
                    OriginalText = originalText,
                    ToolType = ToolType.Basic
                };
            }

            // 搜索操作
            if (description.Contains("搜索") || description.Contains("查找") || description.Contains("寻找"))
            {
                var searchQuery = ExtractSearchQueryFromDescription(description);
                if (!string.IsNullOrEmpty(searchQuery))
                {
                    // 判断是代码搜索还是内容搜索
                    if (description.Contains("代码") || description.Contains("类") || description.Contains("方法"))
                    {
                        return new ToolCall
                        {
                            ToolName = "search-codebase",
                            Parameters = $"{{\"query\":\"{searchQuery}\"}}",
                            OriginalText = originalText,
                            ToolType = ToolType.Advanced
                        };
                    }
                    else
                    {
                        return new ToolCall
                        {
                            ToolName = "smart_search",
                            Parameters = searchQuery,
                            OriginalText = originalText,
                            ToolType = ToolType.Basic
                        };
                    }
                }
            }

            return null;
        }

        private List<ToolCall> InferToolCallsFromText(string text)
        {
            var toolCalls = new List<ToolCall>();
            text = text.ToLower();

            // 分析用户意图的关键词
            var intentPatterns = new Dictionary<string, Func<string, ToolCall?>>
            {
                { @"(创建|新建|写入).*文件", (t) => InferFileCreation(t) },
                { @"(读取|查看|打开).*文件", (t) => InferFileReading(t) },
                { @"(搜索|查找|寻找)", (t) => InferSearch(t) },
                { @"(列出|显示).*目录", (t) => InferDirectoryListing(t) },
                { @"(分析|检查).*代码", (t) => InferCodeAnalysis(t) },
                { @"(网络|联网).*搜索", (t) => InferWebSearch(t) },
                { @"(扫描|分析|查看).*(项目|结构)", (t) => InferProjectStructure(t) },
                { @"(概览|总览|摘要).*(项目)", (t) => InferProjectOverview(t) },
                { @"(创作|写作|续写|生成).*(章节|内容|故事)", (t) => InferContentGeneration(t) },
                { @"(分析|解读).*(故事|情节|角色)", (t) => InferStoryAnalysis(t) }
            };

            foreach (var pattern in intentPatterns)
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(text, pattern.Key))
                {
                    var toolCall = pattern.Value(text);
                    if (toolCall != null)
                    {
                        toolCalls.Add(toolCall);
                    }
                }
            }

            return toolCalls;
        }

        private ToolCall? InferFileCreation(string text)
        {
            // 尝试从文本中提取文件名和内容
            var fileNameMatch = System.Text.RegularExpressions.Regex.Match(text, @"文件[名称]*[：:]\s*([^\s，,。.]+)");
            var contentMatch = System.Text.RegularExpressions.Regex.Match(text, @"内容[：:]\s*(.+)");

            if (fileNameMatch.Success)
            {
                var fileName = fileNameMatch.Groups[1].Value;
                var content = contentMatch.Success ? contentMatch.Groups[1].Value : "// 新建文件";

                return new ToolCall
                {
                    ToolName = "write_file",
                    Parameters = $"{fileName}|{content}",
                    OriginalText = $"[推断]创建文件: {fileName}",
                    ToolType = ToolType.Basic
                };
            }

            return null;
        }

        private ToolCall? InferFileReading(string text)
        {
            // 尝试从文本中提取文件路径
            var fileMatch = System.Text.RegularExpressions.Regex.Match(text, @"([^\s，,。.]+\.(txt|json|cs|xml|md|config))");
            if (fileMatch.Success)
            {
                return new ToolCall
                {
                    ToolName = "read_file",
                    Parameters = fileMatch.Groups[1].Value,
                    OriginalText = $"[推断]读取文件: {fileMatch.Groups[1].Value}",
                    ToolType = ToolType.Basic
                };
            }

            return null;
        }

        private ToolCall? InferSearch(string text)
        {
            // 提取搜索关键词
            var searchMatch = System.Text.RegularExpressions.Regex.Match(text, @"(搜索|查找|寻找)[：:]?\s*([^\s，,。.]+)");
            if (searchMatch.Success)
            {
                var query = searchMatch.Groups[2].Value;

                // 判断是代码搜索还是内容搜索
                if (text.Contains("代码") || text.Contains("类") || text.Contains("方法") || text.Contains("函数"))
                {
                    return new ToolCall
                    {
                        ToolName = "search-codebase",
                        Parameters = $"{{\"query\":\"{query}\"}}",
                        OriginalText = $"[推断]代码搜索: {query}",
                        ToolType = ToolType.Advanced
                    };
                }
                else
                {
                    return new ToolCall
                    {
                        ToolName = "smart_search",
                        Parameters = query,
                        OriginalText = $"[推断]内容搜索: {query}",
                        ToolType = ToolType.Basic
                    };
                }
            }

            return null;
        }

        private ToolCall? InferDirectoryListing(string text)
        {
            return new ToolCall
            {
                ToolName = "list_files",
                Parameters = ".",
                OriginalText = "[推断]列出当前目录",
                ToolType = ToolType.Basic
            };
        }

        private ToolCall? InferCodeAnalysis(string text)
        {
            return new ToolCall
            {
                ToolName = "search-codebase",
                Parameters = "{\"query\":\"class service\"}",
                OriginalText = "[推断]分析代码结构",
                ToolType = ToolType.Advanced
            };
        }

        private ToolCall? InferWebSearch(string text)
        {
            var queryMatch = System.Text.RegularExpressions.Regex.Match(text, @"搜索[：:]?\s*(.+)");
            if (queryMatch.Success)
            {
                var query = queryMatch.Groups[1].Value.Trim();
                return new ToolCall
                {
                    ToolName = "web-search",
                    Parameters = $"{{\"query\":\"{query}\",\"language\":\"zh-CN\"}}",
                    OriginalText = $"[推断]网络搜索: {query}",
                    ToolType = ToolType.Advanced
                };
            }

            return null;
        }

        // 辅助方法：从描述中提取文件路径
        private string? ExtractFilePathFromDescription(string description)
        {
            // 匹配常见的文件路径模式
            var patterns = new[]
            {
                @"([^\s，,。.]+\.(txt|json|cs|xml|md|config|docx|pdf))",
                @"文件[：:]?\s*([^\s，,。.]+)",
                @"路径[：:]?\s*([^\s，,。.]+)"
            };

            foreach (var pattern in patterns)
            {
                var match = System.Text.RegularExpressions.Regex.Match(description, pattern);
                if (match.Success)
                {
                    return match.Groups[1].Value;
                }
            }

            return null;
        }

        // 辅助方法：从描述中提取文件创建信息
        private (string Path, string Content)? ExtractFileCreationInfo(string description)
        {
            var fileNameMatch = System.Text.RegularExpressions.Regex.Match(description, @"文件[名称]*[：:]\s*([^\s，,。.]+)");
            var contentMatch = System.Text.RegularExpressions.Regex.Match(description, @"内容[：:]\s*(.+)");

            if (fileNameMatch.Success)
            {
                var fileName = fileNameMatch.Groups[1].Value;
                var content = contentMatch.Success ? contentMatch.Groups[1].Value : "// 新建文件";
                return (fileName, content);
            }

            // 尝试其他模式
            var simpleMatch = System.Text.RegularExpressions.Regex.Match(description, @"创建\s*([^\s，,。.]+)\s*文件");
            if (simpleMatch.Success)
            {
                return (simpleMatch.Groups[1].Value, "// 新建文件");
            }

            return null;
        }

        // 辅助方法：从描述中提取目录路径
        private string? ExtractDirectoryPathFromDescription(string description)
        {
            var patterns = new[]
            {
                @"目录[：:]?\s*([^\s，,。.]+)",
                @"文件夹[：:]?\s*([^\s，,。.]+)",
                @"路径[：:]?\s*([^\s，,。.]+)"
            };

            foreach (var pattern in patterns)
            {
                var match = System.Text.RegularExpressions.Regex.Match(description, pattern);
                if (match.Success)
                {
                    return match.Groups[1].Value;
                }
            }

            return "."; // 默认当前目录
        }

        // 辅助方法：从描述中提取搜索查询
        private string? ExtractSearchQueryFromDescription(string description)
        {
            var patterns = new[]
            {
                @"搜索[：:]?\s*""([^""]+)""",
                @"查找[：:]?\s*""([^""]+)""",
                @"搜索[：:]?\s*([^\s，,。.]+)",
                @"查找[：:]?\s*([^\s，,。.]+)"
            };

            foreach (var pattern in patterns)
            {
                var match = System.Text.RegularExpressions.Regex.Match(description, pattern);
                if (match.Success)
                {
                    return match.Groups[1].Value;
                }
            }

            return null;
        }

        private async Task<string> ExecuteAdvancedToolAsync(ToolCall toolCall, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation($"开始执行高级工具: {toolCall.ToolName}");

                // 解析参数
                var parameters = ParseToolParameters(toolCall.Parameters);

                _logger.LogDebug($"工具参数解析完成: {parameters.Count} 个参数");

                // 验证工具是否存在
                var availableTools = await _aiToolsService.GetAvailableToolsAsync();
                var tool = availableTools.FirstOrDefault(t => t.Id == toolCall.ToolName);

                if (tool == null)
                {
                    var errorMsg = $"未找到工具: {toolCall.ToolName}";
                    _logger.LogWarning(errorMsg);
                    return errorMsg;
                }

                // 验证参数
                var validation = await _aiToolsService.ValidateParametersAsync(toolCall.ToolName, parameters);
                if (!validation.IsValid)
                {
                    var errorMsg = $"参数验证失败: {string.Join(", ", validation.Errors)}";
                    _logger.LogWarning(errorMsg);
                    return errorMsg;
                }

                // 执行AI工具
                var result = await _aiToolsService.ExecuteToolAsync(toolCall.ToolName, parameters);

                if (result.IsSuccess)
                {
                    _logger.LogInformation($"工具 {toolCall.ToolName} 执行成功，耗时: {result.ExecutionTimeMs}ms");

                    // 提取结果数据
                    var resultText = ExtractToolResult(result);
                    return resultText;
                }
                else
                {
                    var errorMsg = $"工具执行失败: {result.ErrorDetails}";
                    _logger.LogError(errorMsg);
                    return errorMsg;
                }
            }
            catch (OperationCanceledException)
            {
                _logger.LogInformation($"工具 {toolCall.ToolName} 执行被取消");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"执行高级工具 {toolCall.ToolName} 时发生异常");
                return $"工具执行异常: {ex.Message}";
            }
        }

        private Dictionary<string, object> ParseToolParameters(string parametersText)
        {
            var parameters = new Dictionary<string, object>();

            if (string.IsNullOrWhiteSpace(parametersText))
                return parameters;

            try
            {
                // 尝试JSON解析
                var jsonParams = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(parametersText);
                foreach (var kvp in jsonParams)
                {
                    parameters[kvp.Key] = kvp.Value.ValueKind switch
                    {
                        JsonValueKind.String => kvp.Value.GetString() ?? "",
                        JsonValueKind.Number => kvp.Value.GetDouble(),
                        JsonValueKind.True => true,
                        JsonValueKind.False => false,
                        JsonValueKind.Array => kvp.Value.EnumerateArray().Select(e => e.ToString()).ToArray(),
                        _ => kvp.Value.ToString()
                    };
                }
            }
            catch (JsonException)
            {
                // 如果JSON解析失败，尝试简单的键值对解析
                var parts = parametersText.Split('|');
                for (int i = 0; i < parts.Length; i += 2)
                {
                    if (i + 1 < parts.Length)
                    {
                        parameters[parts[i].Trim()] = parts[i + 1].Trim();
                    }
                }
            }

            return parameters;
        }

        private string ExtractToolResult(AIToolExecutionResult result)
        {
            // 优先返回results字段
            if (result.Data.ContainsKey("results"))
            {
                var results = result.Data["results"];
                if (results != null)
                    return results.ToString() ?? result.Message;
            }

            // 其次返回其他数据字段
            if (result.Data.Any())
            {
                var dataText = string.Join("\n", result.Data.Select(kvp => $"{kvp.Key}: {kvp.Value}"));
                return $"{result.Message}\n\n{dataText}";
            }

            // 最后返回消息
            return result.Message;
        }

        private void AddUserMessage(string message)
        {
            var border = new Border { Style = (Style)FindResource("UserMessageStyle") };
            var textBlock = new TextBlock
            {
                Text = message,
                TextWrapping = TextWrapping.Wrap,
                Foreground = Brushes.White
            };
            border.Child = textBlock;

            ChatPanel.Children.Add(border);
            ScrollToBottom();
        }

        private void AddAIMessage(string message)
        {
            var border = new Border { Style = (Style)FindResource("AIMessageStyle") };
            var stackPanel = new StackPanel();

            var header = new TextBlock
            {
                Text = "AI Agent",
                FontWeight = FontWeights.Bold,
                Foreground = (Brush)FindResource("PrimaryHueMidBrush"),
                Margin = new Thickness(0, 0, 0, 4)
            };

            var content = new TextBlock
            {
                Text = message,
                TextWrapping = TextWrapping.Wrap
            };

            stackPanel.Children.Add(header);
            stackPanel.Children.Add(content);
            border.Child = stackPanel;

            ChatPanel.Children.Add(border);
            ScrollToBottom();
        }

        private void AddToolMessage(string message)
        {
            var border = new Border { Style = (Style)FindResource("ToolMessageStyle") };
            var textBlock = new TextBlock
            {
                Text = message,
                TextWrapping = TextWrapping.Wrap,
                FontSize = 12,
                FontStyle = FontStyles.Italic
            };
            border.Child = textBlock;

            ChatPanel.Children.Add(border);
            ScrollToBottom();
        }

        private void ScrollToBottom()
        {
            ChatScrollViewer.ScrollToEnd();
        }

        private void UpdateStatus(string status, Brush color)
        {
            StatusText.Text = status;
            StatusIcon.Foreground = color;
        }

        private void UpdateToolStatus(string status, Brush color)
        {
            // 确保在UI线程中执行
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(() => UpdateToolStatus(status, color));
                return;
            }

            try
            {
                ToolStatusText.Text = status;
                ToolStatusIcon.Foreground = color;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, $"更新工具状态失败: {status}");
            }
        }

        private void AttachFile_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                Title = "选择要分析的文件",
                Filter = "文本文件 (*.txt)|*.txt|Word文档 (*.docx)|*.docx|所有文件 (*.*)|*.*",
                Multiselect = false
            };

            if (openFileDialog.ShowDialog() == true)
            {
                var fileName = Path.GetFileName(openFileDialog.FileName);
                MessageTextBox.Text += $"\n[附件: {fileName}]";
                MessageTextBox.Focus();
            }
        }

        private void ClearChat_Click(object sender, RoutedEventArgs e)
        {
            ChatPanel.Children.Clear();
            _chatHistory.Clear();

            // 重新添加欢迎消息
            InitializeUI();
        }

        private void Settings_Click(object sender, RoutedEventArgs e)
        {
            // TODO: 打开设置对话框
            MessageBox.Show("设置功能即将推出", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            _cancellationTokenSource?.Cancel();
            Close();
        }

        /// <summary>
        /// 添加系统消息（线程安全）
        /// </summary>
        private void AddSystemMessage(string message)
        {
            try
            {
                // 确保在UI线程中执行
                if (!Dispatcher.CheckAccess())
                {
                    Dispatcher.Invoke(() => AddSystemMessage(message));
                    return;
                }

                var systemMessage = new Border
                {
                    Background = new SolidColorBrush(Color.FromRgb(240, 248, 255)),
                    BorderBrush = new SolidColorBrush(Color.FromRgb(173, 216, 230)),
                    BorderThickness = new Thickness(1),
                    CornerRadius = new CornerRadius(8),
                    Padding = new Thickness(12),
                    Margin = new Thickness(0, 4, 0, 4),
                    HorizontalAlignment = HorizontalAlignment.Center,
                    MaxWidth = 400
                };

                var textBlock = new TextBlock
                {
                    Text = $"[系统] {message}",
                    FontSize = 12,
                    Foreground = new SolidColorBrush(Color.FromRgb(70, 130, 180)),
                    TextWrapping = TextWrapping.Wrap,
                    HorizontalAlignment = HorizontalAlignment.Center
                };

                systemMessage.Child = textBlock;
                ChatPanel.Children.Add(systemMessage);

                // 滚动到底部
                ChatScrollViewer.ScrollToEnd();

                _logger?.LogInformation($"添加系统消息: {message}");
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "添加系统消息时发生错误");
            }
        }

        #region 项目选择功能

        /// <summary>
        /// 加载项目列表（统一使用ItemsSource方式）
        /// </summary>
        private async Task LoadProjectsAsync()
        {
            var isInitializing = _availableProjects.Count == 0;

            try
            {
                // 检查项目服务是否可用
                if (_projectService == null)
                {
                    _logger.LogWarning("项目服务不可用，跳过项目列表加载");
                    if (isInitializing)
                    {
                        await InitializeBasicModeAsync();
                    }
                    return;
                }

                if (!isInitializing)
                {
                    UpdateToolStatus("加载项目列表...", Brushes.Orange);
                }

                var projects = await _projectService.GetAllProjectsAsync();

                // 使用统一的ItemsSource方式管理项目列表
                await Dispatcher.InvokeAsync(() =>
                {
                    try
                    {
                        // 清空现有项目列表
                        _availableProjects.Clear();

                        // 添加"无项目"选项
                        _availableProjects.Add(new ProjectInfo
                        {
                            Name = "无项目",
                            Path = "",
                            Type = ProjectType.Unknown,
                            Description = "未选择项目",
                            IsActive = false,
                            FileCount = 0,
                            MarkdownFileCount = 0,
                            Size = 0,
                            CreatedTime = DateTime.Now,
                            LastModifiedTime = DateTime.Now,
                            MainFiles = new List<string>(),
                            Tags = new List<string> { "无项目" }
                        });

                        // 将数据库项目转换为ProjectInfo并添加到列表
                        foreach (var project in projects)
                        {
                            _availableProjects.Add(ConvertToProjectInfo(project));
                        }

                        // 设置ItemsSource（如果还没有设置）
                        if (ProjectSelectionComboBox.ItemsSource != _availableProjects)
                        {
                            ProjectSelectionComboBox.ItemsSource = _availableProjects;
                        }

                        // 如果当前有选中的项目，设置选中状态
                        if (CurrentProject != null)
                        {
                            var matchingItem = _availableProjects.FirstOrDefault(p =>
                                p.Path.Equals(CurrentProject.RootPath, StringComparison.OrdinalIgnoreCase));
                            if (matchingItem != null)
                            {
                                ProjectSelectionComboBox.SelectedItem = matchingItem;
                            }
                        }
                        else
                        {
                            ProjectSelectionComboBox.SelectedIndex = 0; // 选择"无项目"
                        }
                    }
                    catch (Exception uiEx)
                    {
                        _logger.LogError(uiEx, "更新项目列表UI失败");
                        throw;
                    }
                });

                if (!isInitializing)
                {
                    UpdateToolStatus("项目列表已加载", Brushes.Green);
                }
                _logger.LogInformation($"已加载 {projects.Count} 个项目到选择列表");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载项目列表失败");

                // 如果是初始化阶段，静默处理错误并使用基本模式
                if (isInitializing)
                {
                    try
                    {
                        await InitializeBasicModeAsync();
                        return;
                    }
                    catch (Exception basicEx)
                    {
                        _logger.LogError(basicEx, "初始化基本模式失败");
                        UpdateToolStatus("功能受限", Brushes.Red);
                        return;
                    }
                }

                UpdateToolStatus("项目列表加载失败", Brushes.Orange);

                // 提供降级处理 - 至少保证基本功能可用
                try
                {
                    await Dispatcher.InvokeAsync(() =>
                    {
                        // 清空现有项目列表
                        _availableProjects.Clear();

                        // 添加"无项目"选项
                        _availableProjects.Add(new ProjectInfo
                        {
                            Name = "无项目",
                            Path = "",
                            Type = ProjectType.Unknown,
                            Description = "未选择项目",
                            IsActive = false,
                            FileCount = 0,
                            MarkdownFileCount = 0,
                            Size = 0,
                            CreatedTime = DateTime.Now,
                            LastModifiedTime = DateTime.Now,
                            MainFiles = new List<string>(),
                            Tags = new List<string> { "无项目" }
                        });

                        // 如果有当前项目，至少添加当前项目
                        if (CurrentProject != null)
                        {
                            _availableProjects.Add(ConvertToProjectInfo(CurrentProject));
                            ProjectSelectionComboBox.SelectedIndex = 1; // 选择当前项目
                            _logger.LogInformation("已添加当前项目到列表作为备用");
                        }
                        else
                        {
                            ProjectSelectionComboBox.SelectedIndex = 0; // 选择"无项目"
                        }

                        // 设置ItemsSource
                        if (ProjectSelectionComboBox.ItemsSource != _availableProjects)
                        {
                            ProjectSelectionComboBox.ItemsSource = _availableProjects;
                        }
                    });

                    // 显示用户友好的错误消息
                    AddSystemMessage("⚠️ 项目列表加载失败，当前使用基本模式。功能仍可正常使用。");
                }
                catch (Exception fallbackEx)
                {
                    _logger.LogError(fallbackEx, "项目列表降级处理失败");
                    AddSystemMessage("❌ 项目列表功能暂时不可用，请稍后重试。");
                }
            }
        }

        /// <summary>
        /// 项目选择变更事件
        /// </summary>
        private void ProjectSelectionComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                var selectedItem = ProjectSelectionComboBox.SelectedItem;

                if (selectedItem is ProjectInfo projectInfo)
                {
                    // 选择了扫描到的项目
                    _selectedProjectInfo = projectInfo;
                    UpdateProjectInfo();
                    AddSystemMessage($"已切换到项目: {projectInfo.Name} ({projectInfo.TypeDisplayName})");
                    _logger.LogInformation($"用户选择了项目: {projectInfo.Name} at {projectInfo.Path}");
                }
                else if (selectedItem is Project project)
                {
                    // 选择了具体项目
                    CurrentProject = project;
                    _selectedProjectInfo = null;
                    UpdateProjectInfo();
                    AddSystemMessage($"已切换到项目: {project.Name}");
                    _logger.LogInformation($"用户选择项目: {project.Name}");
                }
                else
                {
                    // 选择了"无项目"或其他
                    CurrentProject = null;
                    _selectedProjectInfo = null;
                    UpdateProjectInfo();
                    AddSystemMessage("已退出当前项目");
                    _logger.LogInformation("用户清除了项目选择");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "项目选择变更处理失败");
                AddSystemMessage("项目切换失败，请重试。");
            }
        }

        /// <summary>
        /// 刷新项目列表
        /// </summary>
        private async void RefreshProjects_Click(object sender, RoutedEventArgs e)
        {
            await ScanAndLoadProjectsAsync();
            AddSystemMessage("项目列表已刷新");
        }

        /// <summary>
        /// 浏览自定义目录
        /// </summary>
        private void BrowseDirectory_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 创建自定义的文件夹选择对话框
                var folderDialog = new Microsoft.Win32.OpenFileDialog();
                folderDialog.Title = "选择要在AI助手中操作的项目目录";
                folderDialog.Filter = "文件夹|*.folder";
                folderDialog.FileName = "选择文件夹";
                folderDialog.CheckFileExists = false;
                folderDialog.CheckPathExists = true;
                folderDialog.ValidateNames = false;

                // 设置初始目录
                string initialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                if (_selectedProjectInfo != null && Directory.Exists(_selectedProjectInfo.Path))
                {
                    initialDirectory = _selectedProjectInfo.Path;
                }
                else if (CurrentProject != null && Directory.Exists(CurrentProject.RootPath))
                {
                    initialDirectory = CurrentProject.RootPath;
                }
                folderDialog.InitialDirectory = initialDirectory;

                // 显示对话框
                if (folderDialog.ShowDialog() == true)
                {
                    var selectedPath = Path.GetDirectoryName(folderDialog.FileName);

                    if (!string.IsNullOrEmpty(selectedPath) && Directory.Exists(selectedPath))
                    {
                        // 创建自定义项目信息
                        var customProjectInfo = CreateCustomProjectInfo(selectedPath);

                        // 添加到项目列表（如果不存在）
                        AddCustomProjectToList(customProjectInfo);

                        // 选择这个项目
                        SelectCustomProject(customProjectInfo);

                        AddSystemMessage($"已选择自定义目录: {selectedPath}");
                        _logger.LogInformation($"用户选择了自定义目录: {selectedPath}");
                    }
                    else
                    {
                        // 如果用户没有选择有效目录，提供手动输入选项
                        ShowManualDirectoryInputDialog();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "浏览目录时发生错误");
                MessageBox.Show($"浏览目录时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 显示手动输入目录对话框
        /// </summary>
        private void ShowManualDirectoryInputDialog()
        {
            try
            {
                var inputDialog = new Window
                {
                    Title = "输入项目目录路径",
                    Width = 500,
                    Height = 200,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    Owner = this,
                    ResizeMode = ResizeMode.NoResize
                };

                var grid = new Grid();
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

                var label = new TextBlock
                {
                    Text = "请输入项目目录的完整路径：",
                    Margin = new Thickness(20, 20, 20, 10),
                    FontSize = 14
                };
                Grid.SetRow(label, 0);

                var textBox = new TextBox
                {
                    Margin = new Thickness(20, 0, 20, 10),
                    FontSize = 12,
                    Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                };
                Grid.SetRow(textBox, 1);

                var buttonPanel = new StackPanel
                {
                    Orientation = Orientation.Horizontal,
                    HorizontalAlignment = HorizontalAlignment.Right,
                    Margin = new Thickness(20, 10, 20, 20)
                };

                var okButton = new Button
                {
                    Content = "确定",
                    Width = 80,
                    Height = 30,
                    Margin = new Thickness(0, 0, 10, 0)
                };

                var cancelButton = new Button
                {
                    Content = "取消",
                    Width = 80,
                    Height = 30
                };

                okButton.Click += (s, e) =>
                {
                    var path = textBox.Text.Trim();
                    if (Directory.Exists(path))
                    {
                        var customProjectInfo = CreateCustomProjectInfo(path);
                        AddCustomProjectToList(customProjectInfo);
                        SelectCustomProject(customProjectInfo);
                        AddSystemMessage($"已选择自定义目录: {path}");
                        inputDialog.DialogResult = true;
                        inputDialog.Close();
                    }
                    else
                    {
                        MessageBox.Show("输入的路径不存在，请检查后重新输入。", "路径错误",
                            MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                };

                cancelButton.Click += (s, e) =>
                {
                    inputDialog.DialogResult = false;
                    inputDialog.Close();
                };

                buttonPanel.Children.Add(okButton);
                buttonPanel.Children.Add(cancelButton);
                Grid.SetRow(buttonPanel, 2);

                grid.Children.Add(label);
                grid.Children.Add(textBox);
                grid.Children.Add(buttonPanel);

                inputDialog.Content = grid;
                inputDialog.ShowDialog();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "显示手动输入对话框时发生错误");
            }
        }

        /// <summary>
        /// 清除项目选择
        /// </summary>
        private void ClearProject_Click(object sender, RoutedEventArgs e)
        {
            ProjectSelectionComboBox.SelectedItem = null;
            _selectedProjectInfo = null;
            UpdateProjectInfo();
            AddSystemMessage("已清除项目选择");
        }

        /// <summary>
        /// 创建自定义项目信息
        /// </summary>
        private ProjectInfo CreateCustomProjectInfo(string directoryPath)
        {
            try
            {
                var dirInfo = new DirectoryInfo(directoryPath);
                var files = dirInfo.GetFiles("*", SearchOption.AllDirectories);

                // 分析项目类型
                var projectType = AnalyzeProjectType(files);

                // 计算基本统计信息
                var markdownFiles = files.Where(f => f.Extension.ToLower() == ".md").ToArray();
                var totalSize = files.Sum(f => f.Length);
                var isActive = files.Any(f => f.LastWriteTime > DateTime.Now.AddDays(-30));

                // 获取主要文件
                var mainFiles = GetMainFiles(files, projectType);

                var projectInfo = new ProjectInfo
                {
                    Name = $"[自定义] {dirInfo.Name}",
                    Path = directoryPath,
                    Type = projectType,
                    Description = $"自定义目录项目 - {directoryPath}",
                    CreatedTime = dirInfo.CreationTime,
                    LastModifiedTime = files.Any() ? files.Max(f => f.LastWriteTime) : dirInfo.LastWriteTime,
                    FileCount = files.Length,
                    MarkdownFileCount = markdownFiles.Length,
                    Size = totalSize,
                    IsActive = isActive,
                    MainFiles = mainFiles,
                    Tags = new List<string> { "自定义目录", projectType.ToString() }
                };

                return projectInfo;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建自定义项目信息失败: {directoryPath}");

                // 返回基本项目信息
                return new ProjectInfo
                {
                    Name = $"[自定义] {Path.GetFileName(directoryPath)}",
                    Path = directoryPath,
                    Type = ProjectType.Unknown,
                    Description = $"自定义目录项目 - {directoryPath}",
                    CreatedTime = DateTime.Now,
                    LastModifiedTime = DateTime.Now,
                    Tags = new List<string> { "自定义目录" }
                };
            }
        }

        /// <summary>
        /// 分析项目类型
        /// </summary>
        private ProjectType AnalyzeProjectType(System.IO.FileInfo[] files)
        {
            var extensions = files.Select(f => f.Extension.ToLower()).ToHashSet();

            // 检查是否为小说项目
            if (files.Any(f => f.Name.Contains("章节") || f.Name.Contains("chapter") ||
                              f.Name.Contains("角色") || f.Name.Contains("character")))
            {
                return ProjectType.NovelProject;
            }

            // 检查是否为Markdown项目
            if (extensions.Contains(".md") && files.Count(f => f.Extension.ToLower() == ".md") > files.Length * 0.5)
            {
                return ProjectType.MarkdownProject;
            }

            // 检查是否为代码项目
            var codeExtensions = new[] { ".cs", ".js", ".ts", ".py", ".java", ".cpp", ".c", ".h" };
            if (codeExtensions.Any(ext => extensions.Contains(ext)))
            {
                return ProjectType.CodeProject;
            }

            // 检查是否为文档项目
            var docExtensions = new[] { ".docx", ".doc", ".pdf", ".txt" };
            if (docExtensions.Any(ext => extensions.Contains(ext)))
            {
                return ProjectType.DocumentProject;
            }

            // 混合项目
            if (extensions.Count > 3)
            {
                return ProjectType.MixedProject;
            }

            return ProjectType.Unknown;
        }

        /// <summary>
        /// 获取主要文件列表
        /// </summary>
        private List<string> GetMainFiles(System.IO.FileInfo[] files, ProjectType projectType)
        {
            var mainFiles = new List<string>();

            try
            {
                switch (projectType)
                {
                    case ProjectType.NovelProject:
                        mainFiles.AddRange(files
                            .Where(f => f.Name.Contains("大纲") || f.Name.Contains("outline") ||
                                       f.Name.Contains("章节") || f.Name.Contains("chapter"))
                            .Take(5)
                            .Select(f => f.Name));
                        break;

                    case ProjectType.MarkdownProject:
                        mainFiles.AddRange(files
                            .Where(f => f.Extension.ToLower() == ".md")
                            .OrderByDescending(f => f.LastWriteTime)
                            .Take(5)
                            .Select(f => f.Name));
                        break;

                    case ProjectType.CodeProject:
                        var codeExtensions = new[] { ".cs", ".js", ".ts", ".py", ".java" };
                        mainFiles.AddRange(files
                            .Where(f => codeExtensions.Contains(f.Extension.ToLower()))
                            .OrderByDescending(f => f.LastWriteTime)
                            .Take(5)
                            .Select(f => f.Name));
                        break;

                    default:
                        mainFiles.AddRange(files
                            .OrderByDescending(f => f.LastWriteTime)
                            .Take(5)
                            .Select(f => f.Name));
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取主要文件列表失败");
            }

            return mainFiles;
        }

        /// <summary>
        /// 添加自定义项目到列表
        /// </summary>
        private void AddCustomProjectToList(ProjectInfo customProject)
        {
            try
            {
                var existingItems = ProjectSelectionComboBox.Items.Cast<ProjectInfo>().ToList();

                // 检查是否已存在相同路径的项目
                var existingProject = existingItems.FirstOrDefault(p =>
                    string.Equals(p.Path, customProject.Path, StringComparison.OrdinalIgnoreCase));

                if (existingProject != null)
                {
                    // 更新现有项目信息
                    var index = ProjectSelectionComboBox.Items.IndexOf(existingProject);
                    ProjectSelectionComboBox.Items[index] = customProject;
                }
                else
                {
                    // 添加新项目到列表顶部
                    ProjectSelectionComboBox.Items.Insert(0, customProject);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加自定义项目到列表失败");
            }
        }

        /// <summary>
        /// 选择自定义项目
        /// </summary>
        private void SelectCustomProject(ProjectInfo customProject)
        {
            try
            {
                ProjectSelectionComboBox.SelectedItem = customProject;
                _selectedProjectInfo = customProject;
                UpdateProjectInfo();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "选择自定义项目失败");
            }
        }

        /// <summary>
        /// 设置当前项目（外部调用时同步下拉框选择）
        /// </summary>
        public void SetCurrentProject(Project? project)
        {
            try
            {
                CurrentProject = project;

                // 同步下拉框选择
                if (project != null)
                {
                    var matchingItem = ProjectSelectionComboBox.Items.Cast<object>()
                        .FirstOrDefault(item => item is Project p && p.Id == project.Id);
                    if (matchingItem != null)
                    {
                        ProjectSelectionComboBox.SelectedItem = matchingItem;
                    }
                    else
                    {
                        // 如果项目不在列表中，尝试重新加载项目列表
                        // 使用异步方法但不等待，避免阻塞UI
                        _ = LoadProjectsAsyncSafely(project);
                    }
                }
                else
                {
                    ProjectSelectionComboBox.SelectedIndex = 0; // 选择"无项目"
                }

                UpdateProjectInfo();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"设置当前项目时发生错误: {project?.Name ?? "null"}");
                // 确保项目信息仍然被设置，即使下拉框同步失败
                CurrentProject = project;
                UpdateProjectInfo();
            }
        }

        /// <summary>
        /// 安全地加载项目列表，包含错误处理
        /// </summary>
        private async Task LoadProjectsAsyncSafely(Project? targetProject = null)
        {
            try
            {
                await LoadProjectsAsync();

                // 如果指定了目标项目，尝试再次选中
                if (targetProject != null)
                {
                    var matchingItem = ProjectSelectionComboBox.Items.Cast<object>()
                        .FirstOrDefault(item => item is Project p && p.Id == targetProject.Id);
                    if (matchingItem != null)
                    {
                        ProjectSelectionComboBox.SelectedItem = matchingItem;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "安全加载项目列表失败");
                // 静默失败，不影响用户体验
                // 项目信息已经通过UpdateProjectInfo()设置，功能仍然可用
            }
        }

        #endregion

        // 辅助类
        private class ChatMessage
        {
            public string Role { get; set; } = string.Empty;
            public string Content { get; set; } = string.Empty;
        }

        private class ToolCall
        {
            public string ToolName { get; set; } = string.Empty;
            public string Parameters { get; set; } = string.Empty;
            public string OriginalText { get; set; } = string.Empty;
            public ToolType ToolType { get; set; } = ToolType.Basic;
        }

        private enum ToolType
        {
            Basic,      // 基础工具 [TOOL:工具名]参数[/TOOL]
            Advanced    // 高级工具 [AITOOL:工具ID]{"参数名":"参数值"}[/AITOOL]
        }

        // 智能工具推荐系统相关类
        private class ToolRecommendation
        {
            public ToolCall ToolCall { get; set; } = new();
            public double Confidence { get; set; }
            public string Reason { get; set; } = string.Empty;
        }

        private class UserIntent
        {
            public IntentType Type { get; set; }
            public double Confidence { get; set; }
            public string Context { get; set; } = string.Empty;
        }

        private enum IntentType
        {
            FileOperation,
            Search,
            Analysis,
            WebOperation,
            CodeGeneration,
            DataProcessing
        }

        // 智能工具推荐系统方法
        private async Task<List<ToolRecommendation>> RecommendToolsForResponse(string response)
        {
            var recommendations = new List<ToolRecommendation>();
            var lowerResponse = response.ToLower();

            // 分析响应内容，推荐合适的工具
            var intentAnalysis = AnalyzeUserIntent(lowerResponse);

            foreach (var intent in intentAnalysis)
            {
                var toolRecommendations = await GetToolRecommendationsForIntent(intent);
                recommendations.AddRange(toolRecommendations);
            }

            // 按置信度排序
            return recommendations.OrderByDescending(r => r.Confidence).ToList();
        }

        private List<UserIntent> AnalyzeUserIntent(string text)
        {
            var intents = new List<UserIntent>();

            // 文件操作意图
            if (text.Contains("文件") || text.Contains("创建") || text.Contains("读取") || text.Contains("保存"))
            {
                intents.Add(new UserIntent
                {
                    Type = IntentType.FileOperation,
                    Confidence = CalculateIntentConfidence(text, new[] { "文件", "创建", "读取", "保存", "写入" }),
                    Context = text
                });
            }

            // 搜索意图
            if (text.Contains("搜索") || text.Contains("查找") || text.Contains("寻找"))
            {
                intents.Add(new UserIntent
                {
                    Type = IntentType.Search,
                    Confidence = CalculateIntentConfidence(text, new[] { "搜索", "查找", "寻找", "检索" }),
                    Context = text
                });
            }

            // 分析意图
            if (text.Contains("分析") || text.Contains("检查") || text.Contains("统计"))
            {
                intents.Add(new UserIntent
                {
                    Type = IntentType.Analysis,
                    Confidence = CalculateIntentConfidence(text, new[] { "分析", "检查", "统计", "评估" }),
                    Context = text
                });
            }

            // 网络操作意图
            if (text.Contains("网络") || text.Contains("联网") || text.Contains("在线"))
            {
                intents.Add(new UserIntent
                {
                    Type = IntentType.WebOperation,
                    Confidence = CalculateIntentConfidence(text, new[] { "网络", "联网", "在线", "互联网" }),
                    Context = text
                });
            }

            return intents;
        }

        private double CalculateIntentConfidence(string text, string[] keywords)
        {
            var matchCount = keywords.Count(keyword => text.Contains(keyword));
            var baseConfidence = (double)matchCount / keywords.Length;

            // 根据上下文调整置信度
            if (text.Length > 50) baseConfidence *= 1.1; // 较长的文本通常意图更明确
            if (text.Contains("请") || text.Contains("帮")) baseConfidence *= 1.2; // 明确的请求

            return Math.Min(baseConfidence, 1.0);
        }

        private async Task<List<ToolRecommendation>> GetToolRecommendationsForIntent(UserIntent intent)
        {
            var recommendations = new List<ToolRecommendation>();

            switch (intent.Type)
            {
                case IntentType.FileOperation:
                    recommendations.AddRange(await RecommendFileOperationTools(intent));
                    break;
                case IntentType.Search:
                    recommendations.AddRange(await RecommendSearchTools(intent));
                    break;
                case IntentType.Analysis:
                    recommendations.AddRange(await RecommendAnalysisTools(intent));
                    break;
                case IntentType.WebOperation:
                    recommendations.AddRange(await RecommendWebTools(intent));
                    break;
            }

            return recommendations;
        }

        private async Task<List<ToolRecommendation>> RecommendFileOperationTools(UserIntent intent)
        {
            var recommendations = new List<ToolRecommendation>();
            var context = intent.Context.ToLower();

            if (context.Contains("创建") || context.Contains("新建"))
            {
                recommendations.Add(new ToolRecommendation
                {
                    ToolCall = new ToolCall
                    {
                        ToolName = "write_file",
                        Parameters = "new_file.txt|// 新建文件内容",
                        OriginalText = "[推荐]创建新文件",
                        ToolType = ToolType.Basic
                    },
                    Confidence = intent.Confidence * 0.9,
                    Reason = "检测到文件创建意图"
                });
            }

            if (context.Contains("读取") || context.Contains("查看"))
            {
                recommendations.Add(new ToolRecommendation
                {
                    ToolCall = new ToolCall
                    {
                        ToolName = "list_files",
                        Parameters = ".",
                        OriginalText = "[推荐]列出文件",
                        ToolType = ToolType.Basic
                    },
                    Confidence = intent.Confidence * 0.8,
                    Reason = "检测到文件查看意图"
                });
            }

            return recommendations;
        }

        private async Task<List<ToolRecommendation>> RecommendSearchTools(UserIntent intent)
        {
            var recommendations = new List<ToolRecommendation>();
            var context = intent.Context.ToLower();

            if (context.Contains("代码") || context.Contains("类") || context.Contains("方法"))
            {
                recommendations.Add(new ToolRecommendation
                {
                    ToolCall = new ToolCall
                    {
                        ToolName = "search-codebase",
                        Parameters = "{\"query\":\"搜索关键词\"}",
                        OriginalText = "[推荐]代码搜索",
                        ToolType = ToolType.Advanced
                    },
                    Confidence = intent.Confidence * 0.9,
                    Reason = "检测到代码搜索意图"
                });
            }
            else
            {
                recommendations.Add(new ToolRecommendation
                {
                    ToolCall = new ToolCall
                    {
                        ToolName = "smart_search",
                        Parameters = "搜索关键词",
                        OriginalText = "[推荐]内容搜索",
                        ToolType = ToolType.Basic
                    },
                    Confidence = intent.Confidence * 0.8,
                    Reason = "检测到内容搜索意图"
                });
            }

            return recommendations;
        }

        private async Task<List<ToolRecommendation>> RecommendAnalysisTools(UserIntent intent)
        {
            var recommendations = new List<ToolRecommendation>();

            recommendations.Add(new ToolRecommendation
            {
                ToolCall = new ToolCall
                {
                    ToolName = "content-analyzer",
                    Parameters = "{\"type\":\"general\"}",
                    OriginalText = "[推荐]内容分析",
                    ToolType = ToolType.Advanced
                },
                Confidence = intent.Confidence * 0.7,
                Reason = "检测到分析意图"
            });

            return recommendations;
        }

        private async Task<List<ToolRecommendation>> RecommendWebTools(UserIntent intent)
        {
            var recommendations = new List<ToolRecommendation>();

            recommendations.Add(new ToolRecommendation
            {
                ToolCall = new ToolCall
                {
                    ToolName = "web-search",
                    Parameters = "{\"query\":\"搜索关键词\",\"language\":\"zh-CN\"}",
                    OriginalText = "[推荐]网络搜索",
                    ToolType = ToolType.Advanced
                },
                Confidence = intent.Confidence * 0.8,
                Reason = "检测到网络搜索意图"
            });

            return recommendations;
        }

        private string BuildToolRecommendationMessage(List<ToolRecommendation> recommendations)
        {
            var message = "基于您的需求，我推荐以下工具：\n";
            foreach (var rec in recommendations.Take(3))
            {
                message += $"• {rec.ToolCall.ToolName} (置信度: {rec.Confidence:P0}) - {rec.Reason}\n";
            }
            return message;
        }

        // 工具调用验证和纠错系统
        private async Task<ToolCall?> ValidateAndCorrectToolCall(ToolCall toolCall)
        {
            try
            {
                // 1. 验证工具名称
                var correctedToolName = await ValidateAndCorrectToolName(toolCall.ToolName, toolCall.ToolType);
                if (string.IsNullOrEmpty(correctedToolName))
                {
                    _logger.LogWarning($"无法纠正工具名称: {toolCall.ToolName}");
                    return null;
                }

                // 2. 验证和纠正参数
                var correctedParameters = await ValidateAndCorrectParameters(correctedToolName, toolCall.Parameters, toolCall.ToolType);
                if (correctedParameters == null)
                {
                    _logger.LogWarning($"无法纠正工具参数: {toolCall.ToolName}");
                    return null;
                }

                // 3. 创建纠正后的工具调用
                var correctedToolCall = new ToolCall
                {
                    ToolName = correctedToolName,
                    Parameters = correctedParameters,
                    OriginalText = toolCall.OriginalText,
                    ToolType = toolCall.ToolType
                };

                // 4. 记录纠错信息
                if (correctedToolName != toolCall.ToolName || correctedParameters != toolCall.Parameters)
                {
                    AddToolMessage($"🔧 自动纠错: {toolCall.ToolName} → {correctedToolName}");
                }

                return correctedToolCall;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"验证工具调用时发生错误: {toolCall.ToolName}");
                return null;
            }
        }

        private async Task<string?> ValidateAndCorrectToolName(string toolName, ToolType toolType)
        {
            // 获取所有可用工具
            var availableTools = new List<string>();

            if (toolType == ToolType.Basic)
            {
                // 基础工具列表
                availableTools.AddRange(new[]
                {
                    "read_file", "write_file", "list_files", "delete_file", "move_file",
                    "get_file_info", "create_directory", "find_files", "update_file_content",
                    "smart_search", "batch_update", "analyze_story", "generate_content"
                });
            }
            else
            {
                // 高级工具列表
                var aiTools = await _aiToolsService.GetAvailableToolsAsync();
                availableTools.AddRange(aiTools.Select(t => t.Id));
            }

            // 精确匹配
            if (availableTools.Contains(toolName))
            {
                return toolName;
            }

            // 模糊匹配和纠错
            var bestMatch = FindBestToolMatch(toolName, availableTools);
            if (bestMatch != null)
            {
                _logger.LogInformation($"工具名称纠错: {toolName} → {bestMatch}");
                return bestMatch;
            }

            return null;
        }

        private string? FindBestToolMatch(string inputTool, List<string> availableTools)
        {
            inputTool = inputTool.ToLower().Trim();

            // 1. 完全匹配（忽略大小写）
            var exactMatch = availableTools.FirstOrDefault(t => t.ToLower() == inputTool);
            if (exactMatch != null) return exactMatch;

            // 2. 包含匹配
            var containsMatch = availableTools.FirstOrDefault(t => t.ToLower().Contains(inputTool) || inputTool.Contains(t.ToLower()));
            if (containsMatch != null) return containsMatch;

            // 3. 编辑距离匹配
            var bestMatch = availableTools
                .Select(t => new { Tool = t, Distance = CalculateLevenshteinDistance(inputTool, t.ToLower()) })
                .Where(x => x.Distance <= 3) // 最多允许3个字符差异
                .OrderBy(x => x.Distance)
                .FirstOrDefault();

            return bestMatch?.Tool;
        }

        private int CalculateLevenshteinDistance(string s1, string s2)
        {
            if (string.IsNullOrEmpty(s1)) return s2?.Length ?? 0;
            if (string.IsNullOrEmpty(s2)) return s1.Length;

            var matrix = new int[s1.Length + 1, s2.Length + 1];

            for (int i = 0; i <= s1.Length; i++)
                matrix[i, 0] = i;
            for (int j = 0; j <= s2.Length; j++)
                matrix[0, j] = j;

            for (int i = 1; i <= s1.Length; i++)
            {
                for (int j = 1; j <= s2.Length; j++)
                {
                    int cost = s1[i - 1] == s2[j - 1] ? 0 : 1;
                    matrix[i, j] = Math.Min(
                        Math.Min(matrix[i - 1, j] + 1, matrix[i, j - 1] + 1),
                        matrix[i - 1, j - 1] + cost);
                }
            }

            return matrix[s1.Length, s2.Length];
        }

        private async Task<string?> ValidateAndCorrectParameters(string toolName, string parameters, ToolType toolType)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(parameters))
                {
                    // 为某些工具提供默认参数
                    return GetDefaultParameters(toolName, toolType);
                }

                if (toolType == ToolType.Basic)
                {
                    return ValidateBasicToolParameters(toolName, parameters);
                }
                else
                {
                    return await ValidateAdvancedToolParameters(toolName, parameters);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"验证参数时发生错误: {toolName}");
                return GetDefaultParameters(toolName, toolType);
            }
        }

        private string? GetDefaultParameters(string toolName, ToolType toolType)
        {
            if (toolType == ToolType.Basic)
            {
                return toolName switch
                {
                    "list_files" => ".",
                    "smart_search" => "搜索内容",
                    "write_file" => "new_file.txt|默认内容",
                    "read_file" => "config.json",
                    _ => ""
                };
            }
            else
            {
                return toolName switch
                {
                    "search-codebase" => "{\"query\":\"搜索关键词\"}",
                    "web-search" => "{\"query\":\"搜索关键词\",\"language\":\"zh-CN\"}",
                    "view-files" => "{\"paths\":[\".\"],\"maxFiles\":10}",
                    _ => "{}"
                };
            }
        }

        private string? ValidateBasicToolParameters(string toolName, string parameters)
        {
            // 基础工具参数验证和纠错
            switch (toolName)
            {
                case "write_file":
                    if (!parameters.Contains("|"))
                    {
                        return $"{parameters}|默认内容";
                    }
                    break;

                case "move_file":
                    if (!parameters.Contains("|"))
                    {
                        return $"{parameters}|new_location";
                    }
                    break;

                case "update_file_content":
                    if (!parameters.Contains("|"))
                    {
                        return $"{parameters}|append|新增内容";
                    }
                    break;
            }

            return parameters;
        }

        private async Task<string?> ValidateAdvancedToolParameters(string toolName, string parameters)
        {
            try
            {
                // 尝试解析JSON参数
                var parsedParams = ParseToolParameters(parameters);

                // 验证必需参数
                var validatedParams = await ValidateRequiredParameters(toolName, parsedParams);

                // 重新序列化为JSON
                return System.Text.Json.JsonSerializer.Serialize(validatedParams);
            }
            catch
            {
                // 如果JSON解析失败，尝试修复
                return FixJsonParameters(parameters);
            }
        }

        private async Task<Dictionary<string, object>> ValidateRequiredParameters(string toolName, Dictionary<string, object> parameters)
        {
            // 为不同工具添加必需参数
            switch (toolName)
            {
                case "search-codebase":
                    if (!parameters.ContainsKey("query"))
                        parameters["query"] = "搜索关键词";
                    break;

                case "web-search":
                    if (!parameters.ContainsKey("query"))
                        parameters["query"] = "搜索关键词";
                    if (!parameters.ContainsKey("language"))
                        parameters["language"] = "zh-CN";
                    break;

                case "view-files":
                    if (!parameters.ContainsKey("paths"))
                        parameters["paths"] = new[] { "." };
                    break;
            }

            return parameters;
        }

        private string FixJsonParameters(string parameters)
        {
            // 简单的JSON修复逻辑
            parameters = parameters.Trim();

            if (!parameters.StartsWith("{"))
                parameters = "{" + parameters;
            if (!parameters.EndsWith("}"))
                parameters = parameters + "}";

            // 修复常见的JSON格式问题
            parameters = parameters.Replace("'", "\""); // 单引号改双引号
            parameters = System.Text.RegularExpressions.Regex.Replace(parameters, @"(\w+):", "\"$1\":"); // 添加属性名引号

            return parameters;
        }

        // 思维链处理方法
        private string ProcessThinkingChains(string response)
        {
            try
            {
                // 检查是否包含思维链标签
                if (!response.Contains("<think>") && !response.Contains("<output>"))
                {
                    return response;
                }

                // 提取思维链内容（用于日志记录）
                var thinkingChains = ExtractThinkingChains(response);
                if (thinkingChains.Count > 0)
                {
                    AddToolMessage($"🧠 检测到 {thinkingChains.Count} 个思维链");
                    foreach (var chain in thinkingChains.Take(3)) // 只显示前3个
                    {
                        var preview = chain.Length > 100 ? chain.Substring(0, 100) + "..." : chain;
                        AddToolMessage($"💭 思考: {preview}");
                    }
                }

                // 提取最终输出
                var finalOutput = ExtractFinalOutput(response);
                return !string.IsNullOrEmpty(finalOutput) ? finalOutput : response;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理思维链时发生错误");
                return response;
            }
        }

        private List<string> ExtractThinkingChains(string text)
        {
            var chains = new List<string>();
            var startIndex = 0;

            while (true)
            {
                var thinkStart = text.IndexOf("<think>", startIndex);
                if (thinkStart == -1) break;

                var thinkEnd = text.IndexOf("</think>", thinkStart);
                if (thinkEnd == -1) break;

                var thinkContent = text.Substring(thinkStart + 7, thinkEnd - thinkStart - 7).Trim();
                if (!string.IsNullOrEmpty(thinkContent))
                {
                    chains.Add(thinkContent);
                }

                startIndex = thinkEnd + 8;
            }

            return chains;
        }

        private string ExtractFinalOutput(string text)
        {
            // 查找 <output> 标签
            var outputStart = text.IndexOf("<output>");
            if (outputStart == -1)
            {
                // 如果没有 <output> 标签，移除所有 <think> 内容
                return RemoveThinkingChains(text);
            }

            var outputEnd = text.IndexOf("</output>", outputStart);
            if (outputEnd == -1)
            {
                // 如果没有结束标签，从 <output> 开始到文本结尾
                return text.Substring(outputStart + 8).Trim();
            }

            // 提取 <output> 标签内的内容
            return text.Substring(outputStart + 8, outputEnd - outputStart - 8).Trim();
        }

        private string RemoveThinkingChains(string text)
        {
            var result = text;

            // 移除所有 <think>...</think> 内容
            while (true)
            {
                var thinkStart = result.IndexOf("<think>");
                if (thinkStart == -1) break;

                var thinkEnd = result.IndexOf("</think>", thinkStart);
                if (thinkEnd == -1) break;

                result = result.Remove(thinkStart, thinkEnd - thinkStart + 8);
            }

            return result.Trim();
        }

        // 性能报告相关方法
        private void ShowPerformanceReport()
        {
            try
            {
                var report = _performanceMonitor.GeneratePerformanceReport();
                var stats = _performanceMonitor.GetStatistics();

                var reportWindow = new Window
                {
                    Title = "工具调用性能报告",
                    Width = 800,
                    Height = 600,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    Owner = this
                };

                var scrollViewer = new ScrollViewer
                {
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                    HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                    Padding = new Thickness(10)
                };

                var textBlock = new TextBlock
                {
                    Text = report,
                    FontFamily = new System.Windows.Media.FontFamily("Consolas"),
                    FontSize = 12,
                    TextWrapping = TextWrapping.Wrap
                };

                scrollViewer.Content = textBlock;
                reportWindow.Content = scrollViewer;

                reportWindow.ShowDialog();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "显示性能报告时发生错误");
                MessageBox.Show($"显示性能报告失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ClearPerformanceData()
        {
            try
            {
                _performanceMonitor.ClearStatistics();
                AddToolMessage("📊 性能统计数据已清除");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清除性能数据时发生错误");
                AddToolMessage($"❌ 清除性能数据失败: {ex.Message}");
            }
        }

        // 添加快捷键支持
        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F12 && Keyboard.Modifiers == ModifierKeys.Control)
            {
                // Ctrl+F12 显示性能报告
                ShowPerformanceReport();
                e.Handled = true;
            }
            else if (e.Key == Key.F12 && Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Shift))
            {
                // Ctrl+Shift+F12 清除性能数据
                ClearPerformanceData();
                e.Handled = true;
            }
        }

        #region 项目扫描和选择功能

        /// <summary>
        /// 扫描并加载项目列表
        /// </summary>
        private async Task ScanAndLoadProjectsAsync()
        {
            var isInitializing = ProjectSelectionComboBox.ItemsSource == null;

            try
            {
                if (!isInitializing)
                {
                    UpdateToolStatus("正在扫描项目...", Brushes.Orange);
                }

                // 检查项目扫描服务是否可用
                if (_projectScanService == null)
                {
                    _logger.LogWarning("项目扫描服务不可用，跳过项目扫描");
                    await InitializeBasicModeAsync();
                    return;
                }

                // 扫描当前工作目录和常见项目目录
                var scanTasks = new List<Task<ProjectScanResult>>();
                var successfulScans = 0;

                try
                {
                    // 扫描当前目录
                    var currentDir = Directory.GetCurrentDirectory();
                    if (Directory.Exists(currentDir))
                    {
                        scanTasks.Add(_projectScanService.ScanProjectsAsync(currentDir, 2));
                    }

                    // 扫描父目录
                    var parentDir = Directory.GetParent(currentDir)?.FullName;
                    if (!string.IsNullOrEmpty(parentDir) && Directory.Exists(parentDir))
                    {
                        scanTasks.Add(_projectScanService.ScanProjectsAsync(parentDir, 1));
                    }

                    // 扫描用户文档目录
                    var documentsDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    if (Directory.Exists(documentsDir))
                    {
                        scanTasks.Add(_projectScanService.ScanProjectsAsync(documentsDir, 2));
                    }

                    if (scanTasks.Count == 0)
                    {
                        _logger.LogWarning("没有可扫描的目录");
                        await InitializeBasicModeAsync();
                        return;
                    }

                    // 等待所有扫描完成，但允许部分失败
                    var results = await Task.WhenAll(scanTasks);

                    // 合并结果
                    _availableProjects.Clear();
                    foreach (var result in results)
                    {
                        if (result.IsSuccess)
                        {
                            _availableProjects.AddRange(result.Projects);
                            successfulScans++;
                        }
                        else
                        {
                            _logger.LogWarning($"项目扫描部分失败: {string.Join(", ", result.Errors)}");
                        }
                    }

                    // 去重并排序
                    _availableProjects = _availableProjects
                        .GroupBy(p => p.Path)
                        .Select(g => g.First())
                        .OrderByDescending(p => p.IsActive)
                        .ThenBy(p => p.Type)
                        .ThenBy(p => p.Name)
                        .ToList();
                }
                catch (Exception scanEx)
                {
                    _logger.LogError(scanEx, "项目扫描过程中发生错误");
                    // 如果是初始化阶段，使用基本模式
                    if (isInitializing)
                    {
                        await InitializeBasicModeAsync();
                        return;
                    }
                }

                // 如果当前有项目但扫描失败，至少添加当前项目到列表
                if (_availableProjects.Count == 0 && CurrentProject != null)
                {
                    try
                    {
                        var currentProjectInfo = CreateBasicProjectInfo(CurrentProject);
                        _availableProjects.Add(currentProjectInfo);
                        _logger.LogInformation("添加当前项目到扫描结果作为备用");
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "创建基本项目信息失败");
                    }
                }

                // 更新UI
                Dispatcher.Invoke(() =>
                {
                    try
                    {
                        // 保存当前选择的项目信息
                        var currentProjectPath = CurrentProject?.RootPath;
                        var currentProjectName = CurrentProject?.Name;

                        // 临时禁用SelectionChanged事件处理
                        ProjectSelectionComboBox.SelectionChanged -= ProjectSelectionComboBox_SelectionChanged;

                        try
                        {
                            ProjectSelectionComboBox.ItemsSource = _availableProjects;

                            // 如果当前有项目，尝试选中
                            if (!string.IsNullOrEmpty(currentProjectPath))
                            {
                                var matchingProject = _availableProjects.FirstOrDefault(p =>
                                    p.Path.Equals(currentProjectPath, StringComparison.OrdinalIgnoreCase) ||
                                    p.Name.Equals(currentProjectName, StringComparison.OrdinalIgnoreCase));

                                if (matchingProject != null)
                                {
                                    ProjectSelectionComboBox.SelectedItem = matchingProject;
                                    _logger.LogInformation($"重新选中项目: {matchingProject.Name}");
                                }
                                else
                                {
                                    // 如果找不到匹配的项目，保持当前项目不变
                                    _logger.LogWarning($"扫描结果中未找到当前项目: {currentProjectName}，保持当前选择");
                                    // 不改变ProjectSelectionComboBox的选择，保持CurrentProject不变
                                }
                            }
                        }
                        finally
                        {
                            // 重新启用SelectionChanged事件处理
                            ProjectSelectionComboBox.SelectionChanged += ProjectSelectionComboBox_SelectionChanged;
                        }
                    }
                    catch (Exception uiEx)
                    {
                        _logger.LogError(uiEx, "更新项目选择UI失败");
                    }
                });

                var statusMessage = successfulScans > 0
                    ? $"找到 {_availableProjects.Count} 个项目 ({successfulScans}/{scanTasks.Count} 扫描成功)"
                    : "项目扫描完成，使用基本模式";

                UpdateToolStatus(statusMessage, successfulScans > 0 ? Brushes.Green : Brushes.Orange);
                _logger.LogInformation($"项目扫描完成，找到 {_availableProjects.Count} 个项目，{successfulScans}/{scanTasks.Count} 扫描成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "扫描项目时发生严重错误");

                // 如果是初始化阶段，使用基本模式
                if (isInitializing)
                {
                    try
                    {
                        await InitializeBasicModeAsync();
                        return;
                    }
                    catch (Exception basicEx)
                    {
                        _logger.LogError(basicEx, "初始化基本模式失败");
                        UpdateToolStatus("功能受限", Brushes.Red);
                        return;
                    }
                }

                UpdateToolStatus("项目扫描失败，使用基本模式", Brushes.Orange);

                // 提供最基本的功能 - 如果有当前项目，至少显示它
                if (CurrentProject != null)
                {
                    try
                    {
                        var basicProjectInfo = CreateBasicProjectInfo(CurrentProject);
                        _availableProjects.Clear();
                        _availableProjects.Add(basicProjectInfo);

                        Dispatcher.Invoke(() =>
                        {
                            ProjectSelectionComboBox.ItemsSource = _availableProjects;
                            ProjectSelectionComboBox.SelectedItem = basicProjectInfo;
                        });

                        _logger.LogInformation("已启用基本项目模式");
                    }
                    catch (Exception fallbackEx)
                    {
                        _logger.LogError(fallbackEx, "启用基本项目模式失败");
                    }
                }
            }
        }

        /// <summary>
        /// 创建基本项目信息（用于错误恢复）
        /// </summary>
        private ProjectInfo CreateBasicProjectInfo(Project project)
        {
            return new ProjectInfo
            {
                Name = project.Name,
                Path = project.RootPath ?? "",
                Type = ConvertProjectType(project.Type),
                Description = $"基本项目信息 - {project.Description ?? "无描述"}",
                CreatedTime = project.CreatedAt,
                LastModifiedTime = project.UpdatedAt,
                IsActive = true,
                FileCount = 0,
                MarkdownFileCount = 0,
                Size = 0,
                MainFiles = new List<string>(),
                Tags = new List<string> { "基本模式" }
            };
        }

        /// <summary>
        /// 将Project转换为ProjectInfo
        /// </summary>
        private ProjectInfo ConvertToProjectInfo(Project project)
        {
            return new ProjectInfo
            {
                Name = project.Name,
                Path = project.RootPath ?? "",
                Type = ConvertProjectType(project.Type),
                Description = project.Description ?? "无描述",
                CreatedTime = project.CreatedAt,
                LastModifiedTime = project.UpdatedAt,
                IsActive = project.Status == "Active",
                FileCount = 0, // 可以后续优化为实际统计
                MarkdownFileCount = 0,
                Size = 0,
                MainFiles = new List<string>(),
                Tags = new List<string> { GetProjectTypeDisplayName(project.Type ?? "Unknown") }
            };
        }

        /// <summary>
        /// 转换项目类型
        /// </summary>
        private ProjectType ConvertProjectType(string? projectType)
        {
            return projectType switch
            {
                "Novel" => ProjectType.NovelProject,
                "Normal" => ProjectType.DocumentProject,
                "Markdown" => ProjectType.MarkdownProject,
                "Code" => ProjectType.CodeProject,
                "Mixed" => ProjectType.MixedProject,
                _ => ProjectType.Unknown
            };
        }

        /// <summary>
        /// 获取项目类型显示名称
        /// </summary>
        private string GetProjectTypeDisplayName(string projectType)
        {
            return projectType switch
            {
                "Novel" => "小说项目",
                "Normal" => "文档项目",
                "Markdown" => "Markdown项目",
                "Code" => "代码项目",
                "Mixed" => "混合项目",
                _ => "未知类型"
            };
        }

        /// <summary>
        /// 紧急错误恢复机制
        /// </summary>
        private async Task EmergencyRecoveryAsync(string errorContext, Exception ex)
        {
            try
            {
                _logger.LogError(ex, $"执行紧急错误恢复: {errorContext}");

                await Dispatcher.InvokeAsync(() =>
                {
                    try
                    {
                        // 重置UI状态
                        UpdateToolStatus("紧急恢复中...", Brushes.Orange);

                        // 确保项目列表至少有基本选项
                        if (_availableProjects.Count == 0)
                        {
                            _availableProjects.Add(new ProjectInfo
                            {
                                Name = "无项目",
                                Path = "",
                                Type = ProjectType.Unknown,
                                Description = "紧急恢复模式",
                                IsActive = false,
                                FileCount = 0,
                                MarkdownFileCount = 0,
                                Size = 0,
                                CreatedTime = DateTime.Now,
                                LastModifiedTime = DateTime.Now,
                                MainFiles = new List<string>(),
                                Tags = new List<string> { "紧急恢复" }
                            });

                            ProjectSelectionComboBox.ItemsSource = _availableProjects;
                            ProjectSelectionComboBox.SelectedIndex = 0;
                        }

                        // 显示恢复状态
                        UpdateToolStatus("紧急恢复完成", Brushes.Yellow);
                        AddSystemMessage($"⚠️ 系统已从错误中恢复: {errorContext}");

                        _logger.LogInformation($"紧急错误恢复完成: {errorContext}");
                    }
                    catch (Exception uiEx)
                    {
                        _logger.LogError(uiEx, "紧急恢复UI操作失败");

                        // 最后的备用方案
                        try
                        {
                            UpdateToolStatus("功能受限", Brushes.Red);
                        }
                        catch (Exception finalEx)
                        {
                            _logger.LogError(finalEx, "最终状态更新也失败");
                        }
                    }
                });
            }
            catch (Exception recoveryEx)
            {
                _logger.LogError(recoveryEx, "紧急错误恢复失败");

                // 记录严重错误，但不再抛出异常
                _logger.LogCritical("Agent助手进入严重错误状态，功能可能完全不可用");
            }
        }

        /// <summary>
        /// 检查系统健康状态
        /// </summary>
        private bool CheckSystemHealth()
        {
            try
            {
                // 检查关键组件
                bool isHealthy = true;

                if (ProjectSelectionComboBox == null)
                {
                    _logger.LogWarning("项目选择控件未初始化");
                    isHealthy = false;
                }

                if (_availableProjects == null)
                {
                    _logger.LogWarning("项目列表未初始化");
                    isHealthy = false;
                }

                if (ChatPanel == null)
                {
                    _logger.LogWarning("聊天面板未初始化");
                    isHealthy = false;
                }

                if (ToolStatusText == null)
                {
                    _logger.LogWarning("状态文本控件未初始化");
                    isHealthy = false;
                }

                return isHealthy;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "系统健康检查失败");
                return false;
            }
        }









        /// <summary>
        /// 获取当前项目上下文信息
        /// </summary>
        private string GetCurrentProjectContext()
        {
            if (_selectedProjectInfo != null)
            {
                var fileInfo = _selectedProjectInfo.FileCount > 0 ?
                    $"包含 {_selectedProjectInfo.FileCount} 个文件" : "空项目";

                var markdownInfo = _selectedProjectInfo.MarkdownFileCount > 0 ?
                    $"，其中 {_selectedProjectInfo.MarkdownFileCount} 个Markdown文件" : "";

                var sizeInfo = _selectedProjectInfo.Size > 0 ?
                    $"，总大小 {_selectedProjectInfo.FormattedSize}" : "";

                var activeInfo = _selectedProjectInfo.IsActive ? "（活跃项目）" : "（非活跃项目）";

                return $@"- **当前项目**: {_selectedProjectInfo.Name} ({_selectedProjectInfo.TypeDisplayName})
- **项目路径**: {_selectedProjectInfo.RelativePath}
- **项目信息**: {fileInfo}{markdownInfo}{sizeInfo} {activeInfo}
- **主要文件**: {string.Join(", ", _selectedProjectInfo.MainFiles.Take(3))}
- **项目标签**: {string.Join(", ", _selectedProjectInfo.Tags)}";
            }
            else if (CurrentProject != null)
            {
                return $@"- **当前项目**: {CurrentProject.Name}
- **项目路径**: {CurrentProject.RootPath}
- **项目描述**: {CurrentProject.Description}";
            }
            else
            {
                return "- **当前项目**: 未选择项目，工作在默认目录";
            }
        }

        /// <summary>
        /// 推断项目结构扫描
        /// </summary>
        private ToolCall? InferProjectStructure(string text)
        {
            return new ToolCall
            {
                ToolName = "scan_project_structure",
                Parameters = "",
                OriginalText = "[推断]扫描项目结构",
                ToolType = ToolType.Basic
            };
        }

        /// <summary>
        /// 推断项目概览
        /// </summary>
        private ToolCall? InferProjectOverview(string text)
        {
            return new ToolCall
            {
                ToolName = "get_project_overview",
                Parameters = "",
                OriginalText = "[推断]获取项目概览",
                ToolType = ToolType.Basic
            };
        }

        /// <summary>
        /// 推断内容生成
        /// </summary>
        private ToolCall? InferContentGeneration(string text)
        {
            // 根据当前项目类型推断内容生成类型
            var contentType = "general";
            if (_selectedProjectInfo?.Type == ProjectType.NovelProject)
            {
                contentType = "story";
            }
            else if (_selectedProjectInfo?.Type == ProjectType.MarkdownProject)
            {
                contentType = "documentation";
            }

            return new ToolCall
            {
                ToolName = "generate_content",
                Parameters = $"type:{contentType}",
                OriginalText = "[推断]生成内容",
                ToolType = ToolType.Basic
            };
        }

        /// <summary>
        /// 处理诡异收藏家项目分析请求
        /// </summary>
        private async Task HandleGuiYiProjectAnalysisAsync()
        {
            try
            {
                UpdateToolStatus("🔍 正在分析诡异收藏家项目...", Brushes.Orange);

                var analysisResult = await _toolCompatibilityService.AnalyzeGuiYiProject();

                AddAIMessage("📚 **诡异收藏家项目分析完成**\n\n" + analysisResult);

                UpdateToolStatus("✅ 项目分析完成", Brushes.Green);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "诡异收藏家项目分析失败");
                AddAIMessage($"❌ 项目分析失败: {ex.Message}");
                UpdateToolStatus("❌ 分析失败", Brushes.Red);
            }
        }

        /// <summary>
        /// 显示工具使用指南
        /// </summary>
        private void ShowToolGuide()
        {
            try
            {
                var guide = _toolCompatibilityService.GenerateToolGuide();
                AddAIMessage(guide);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成工具指南失败");
                AddAIMessage($"❌ 生成工具指南失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 添加欢迎消息
        /// </summary>
        private void AddWelcomeMessage()
        {
            var welcomeMessage = @"🤖 **AI助手已就绪！**

✨ **新功能**: 现在支持原生不带函数调用的AI模型使用工具！

🛠️ **基础工具**:
• `scan_project_structure()` - 扫描项目结构
• `get_project_overview()` - 获取项目概览
• `deep_content_search(关键词)` - 深度内容搜索
• `analyze_file_relationships()` - 分析文件关系

🔍 **增强文件访问工具**:
• `get_path_info(路径)` - 获取路径详细信息
• `smart_file_access(文件路径)` - 智能文件访问
• `search_paths(路径|模式)` - 搜索文件和目录
• `batch_file_info(文件列表)` - 批量文件信息
• `analyze_directory_structure(目录)` - 深度目录分析

📊 **智能特性**:
- 🧠 自动判断文件访问策略（完整/部分/预览/摘要）
- 📏 根据文件大小智能选择读取方式
- 🔍 支持复杂路径搜索和批量操作
- 📈 提供详细的文件统计和分析

📚 **诡异收藏家项目专项分析**:
如果您想分析'诡异收藏家'项目，可以直接说：
""请分析诡异收藏家项目的结构和内容""

💡 **使用提示**:
- 直接在对话中使用工具调用语法，如: `smart_file_access(第一章.txt)`
- 系统会自动识别并执行工具调用
- 支持带参数和不带参数的调用方式
- 模型会自主判断是否需要完整或部分访问文件

输入 ""工具指南"" 查看详细使用说明。";

            AddAIMessage(welcomeMessage);
        }

        /// <summary>
        /// 处理特殊命令
        /// </summary>
        /// <param name="message">用户消息</param>
        /// <returns>是否处理了特殊命令</returns>
        private async Task<bool> HandleSpecialCommandsAsync(string message)
        {
            var lowerMessage = message.ToLower().Trim();

            try
            {
                switch (lowerMessage)
                {
                    case "工具指南":
                    case "tool guide":
                    case "help":
                        ShowToolGuide();
                        return true;

                    case "分析诡异收藏家":
                    case "诡异收藏家分析":
                    case "analyze guiyi":
                        await HandleGuiYiProjectAnalysisAsync();
                        return true;

                    case "项目结构":
                    case "scan structure":
                        var structureResult = await _toolCompatibilityService.ProcessToolCallsAsync("scan_project_structure()");
                        AddAIMessage(structureResult);
                        return true;

                    case "项目概览":
                    case "project overview":
                        var overviewResult = await _toolCompatibilityService.ProcessToolCallsAsync("get_project_overview()");
                        AddAIMessage(overviewResult);
                        return true;

                    case "文件关系":
                    case "file relationships":
                        var relationshipResult = await _toolCompatibilityService.ProcessToolCallsAsync("analyze_file_relationships()");
                        AddAIMessage(relationshipResult);
                        return true;
                }

                // 检查是否包含诡异收藏家相关的分析请求
                if (lowerMessage.Contains("诡异收藏家") && (lowerMessage.Contains("分析") || lowerMessage.Contains("结构") || lowerMessage.Contains("内容")))
                {
                    await HandleGuiYiProjectAnalysisAsync();
                    return true;
                }

                // 检查是否直接包含工具调用
                if (_toolCompatibilityService.ContainsToolCalls(message))
                {
                    var currentProjectPath = CurrentProject?.RootPath ?? _selectedProjectInfo?.Path;
                    var result = await _toolCompatibilityService.ProcessToolCallsAsync(message, currentProjectPath);
                    AddAIMessage(result);
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理特殊命令失败: {message}");
                AddAIMessage($"❌ 处理命令失败: {ex.Message}");
                return true; // 返回true避免进一步处理
            }
        }

        /// <summary>
        /// 推断故事分析
        /// </summary>
        private ToolCall? InferStoryAnalysis(string text)
        {
            return new ToolCall
            {
                ToolName = "analyze_story",
                Parameters = "",
                OriginalText = "[推断]分析故事内容",
                ToolType = ToolType.Basic
            };
        }



        #endregion
    }
}
